- Don't add code cruft. Avoid parentheses around conditions in if-statements or with the
return
keyword. Don't add semicolons except where syntactically demanded in statements or to separate statements on the same line. - Don't use ALL_CAPS; use camelCase
- Don't fight type inference. Use enumeration prefixes, self-references, and class names (with constructors) only when necessary or to clarify coding intent.
- Don't use
var
whenlet
is appropriate, especially for properties. The compiler better optimizeslet
statements for items whose values will not change during their lifetime. For example, Apple writes, "It is good practice to create immutable collections in all cases where the collection does not need to change. Doing so enables the Swift compiler to optimize the performance of the collections you create." - Don't use classes when structs will do. Use classes if you want reference types. Use structs if you want value types. You can add functionality to both (and to enumerations) in Swift. When in doubt, err on the side of value types. If your construct doesn't have a life cycle, or two constructs with similar values should be considered as the same thing, use a struct.
- Don't use fallback values when what you really want are optionals. If you're working hard to avoid nil checks, you're doing Swift wrong.
- Don't forget access controls, especially for top-level definitions. Access controls ensure your code can be re-used and modularized.
- Don't be unnecessarily verbose. Use inferred
get
clauses (for properties), anonymous arguments (e.g. $0, skipping the type in bits for closures), etc to clean up your code. - Don't use Allman. http://en.wikipedia.org/wiki/Indent_style#Variant:_1TBS is your Swift style.
- Don't avoid Foundation and Cocoa. At the same time, use Swift native types whenever possible.
- Don't use
CGPointMake()
. Prefer Swift constructors and initializers over legacy ones. - Don't use unnecessary variables. The wildcard expression (_) ignores values during assignments. Use it to skip items that are not referenced in the called scope, e.g. let (status, _) = GetInfo() or for _ in 1...5 {//do something 5 times}
- Don't fear uppercase. Use TitleCase for types and enum variants.
Thanks, Lily Ballard