Skip to content

Instantly share code, notes, and snippets.

@dhoerl dhoerl/DavidTop10
Created May 13, 2015

What would you like to do?
Swift: David's Top 10 "Do This" List
David's Top 10: Do That When Writing Swift
1) Purchase Dash (OS X and iOS) and get Swift from (invaluable reference, I use it daily!)
2) Use Enums for UIView tags and SegmentedControl segments;
enum MyViews: Int { case OKButton=1...} then switch MyViews(rawValue: view.tag)
also for states (somewhat replaces C's X-Macros, helps during debugging)
enum State: String { case Idle = "Idle" ...} ;
let s: State = State(rawValue: "Idle")!; println("\(s.rawValue)") // Idle
3) When objects need configuration, you can use closures:
lazy var object: Foo = { let foo=Foo(delegate: self); foo.x = "y"; return foo;} ()
Benefit: moves "hidden" initializer code in viewDidLoad/etc to top of class.
4) Add main and after to your Code Snippets - big time saver if you use them often:
dispatch_async(dispatch_get_main_queue()) { /* new line */ }
let t = dispatch_time(DISPATCH_TIME_NOW, Int64(250 * NSEC_PER_MSEC))
dispatch_after(t, dispatch_get_main_queue()) { /* new line */ }
5) Use same variable name with optional unwrapping (a 'best practice'): if let user = user {...
6) Use "#if true" and "if true" to your advantage. Former to enable/disable chunks of code (but leave them readable),
the latter replaces C's "{...}" scoping blocks.
7) Switches are syntactic sugar for a list of if and else if statements - most probable should be first in performance
sensitive code. Long cases with a often hit default case can be a problem (C often uses jump tables for switches).
8) Never forget: Arrays, Dictionaries, and Sets are all values! If changing a structure in an array,
get it, change it, write it back.
9) Use the extended if let style (from Nate Cook, NSHipster), new in Swift 1.2:
if let
a = b where yada yada,
c = d where blah blah // can prefix 'let if you really want to
{ // each clause must be unwrapping an optional with no general logic allowed except in the where section
10) Add a 'nullability' Code Snippet - then use it in your older Objective C code
#if __has_feature(nullability)
// For Object pointers
#define nullable
#define nonnull
// For C pointers
#define __nullable
#define __nonnull
#if __has_feature(nullability)
Bonus read: Erica Sadun's "Don't do list"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.