- Notifications
You must be signed in to change notification settings - Fork0
The "official" Swift style guide for Mindera ❤️
License
Mindera/swift-style-guide
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
(Based on raywanderlich.com swift style guide ❤️)
- The Mindera Swift Style Guide
- Table of Contents
- Correctness
- Naming
- Code Organization
- Spacing
- Comments
- Classes and Structures
- Type aliases
- Function Declarations
- Function Calls
- Closure Expressions
- Types
- Functions vs Methods
- Memory Management
- Access Control
- Attributes
- Control Flow
- Golden Path
- Semicolons
- Parentheses
- String Literals
- Organization and Bundle Identifier
- References
Strive to make your code compile without warnings. This rule informs many style decisions such as using#selector
types instead of string literals.
Descriptive and consistent naming makes software easier to read and understand. Use the Swift naming conventions described in theAPI Design Guidelines. Some key takeaways include:
- striving for clarity at the call site
- prioritizing clarity over brevity
- using camel case (not snake case)
- using uppercase for types (and protocols), lowercase for everything else
- including all needed words while omitting needless words
- using names based on roles, not types
- sometimes compensating for weak type information
- striving for fluent usage
- beginning factory methods with
make
- naming methods for their side effects
- verb methods follow the -ed, -ing rule for the non-mutating version
- noun methods follow the formX rule for the mutating version
- boolean types should read like assertions
- protocols that describewhat something is should read as nouns
- protocols that describea capability should end in-able or-ible
- using terms that don't surprise experts or confuse beginners
- generally avoiding abbreviations
- using precedent for names
- preferring methods and properties to free functions
- casing acronyms and initialisms uniformly up or down
- giving the same base name to methods that share the same meaning
- avoiding overloads on return type
- choosing good parameter names that serve as documentation
- preferring to name the first parameter instead of including its name in the method name, except as mentioned under Delegates
- labeling closure and tuple parameters
- taking advantage of default parameters
When referring to methods in prose, being unambiguous is critical. To refer to a method name, use the simplest form possible.
- Write the method name with no parameters.Example: Next, you need to call
addTarget
. - Write the method name with argument labels.Example: Next, you need to call
addTarget(_:action:)
. - Write the full method name with argument labels and types.Example: Next, you need to call
addTarget(_: Any?, action: Selector?)
.
For the above example usingUIGestureRecognizer
, 1 is unambiguous and preferred.
Pro Tip: You can use Xcode's jump bar to lookup methods with argument labels. If you’re particularly good at mashing lots of keys simultaneously, put the cursor in the method name and pressShift-Control-Option-Command-C (all 4 modifier keys) and Xcode will kindly put the signature on your clipboard.
Swift types are automatically namespaced by the module that contains them and you should not add a class prefix such as MND. If two names from different modules collide you can disambiguate by prefixing the type name with the module name. However, only specify the module name when there is possibility for confusion which should be rare.
import SomeModuleletmyClass=MyModule.UsefulClass()
When creating custom delegate methods, an unnamed first parameter should be the delegate source. (UIKit contains numerous examples of this.)
Preferred:
func namePickerView(_ namePickerView:NamePickerView, didSelectName name:String)func namePickerViewShouldReload(_ namePickerView:NamePickerView)->Bool
Not Preferred:
func didSelectName(namePicker:NamePickerViewController, name:String)func namePickerShouldReload()->Bool
Use compiler inferred context to write shorter, clear code. (Also seeType Inference.)
Preferred:
letselector= #selector(viewDidLoad)view.backgroundColor=.redlettoView= context.view(forKey:.to)letview=UIView(frame:.zero)
Not Preferred:
letselector= #selector(ViewController.viewDidLoad)view.backgroundColor=UIColor.redlettoView= context.view(forKey:UITransitionContextViewKey.to)letview=UIView(frame:CGRect.zero)
Generic type parameters should be descriptive, upper camel case names. When a type name doesn't have a meaningful relationship or role, use a traditional single uppercase letter such asT
,U
, orV
.
Preferred:
structStack<Element>{...}func write<Target:OutputStream>(to target:inoutTarget)func swap<T>(_ a:inoutT, _ b:inoutT)
Not Preferred:
structStack<T>{...}func write<target:OutputStream>(to target:inouttarget)func swap<Thing>(_ a:inoutThing, _ b:inoutThing)
Use US English spelling to match Apple's API.
Preferred:
letcolor="red"
Not Preferred:
letcolour="red"
Use extensions to organize your code into logical blocks of functionality. Each extension should be set off with a// MARK: -
comment to keep things well-organized.
In particular, when adding protocol conformance to a model, prefer adding a separate extension for the protocol methods. This keeps the related methods grouped together with the protocol and can simplify instructions to add a protocol to a class with its associated methods.
Preferred:
classMyViewController:UIViewController{ // class stuff here}// MARK: - UITableViewDataSourceextensionMyViewController:UITableViewDataSource{ // table view data source methods}// MARK: - UIScrollViewDelegateextensionMyViewController:UIScrollViewDelegate{ // scroll view delegate methods}
Not Preferred:
classMyViewController:UIViewController,UITableViewDataSource,UIScrollViewDelegate{ // all methods}
Since the compiler does not allow you to re-declare protocol conformance in a derived class, it is not always required to replicate the extension groups of the base class. This is especially true if the derived class is a terminal class and a small number of methods are being overridden. When to preserve the extension groups is left to the discretion of the developer.
For UIKit view controllers, consider grouping lifecycle, custom accessors, and IBAction in separate class extensions.
Unused (dead) code, including Xcode template code and placeholder comments should be removed
Methods that simply call the superclass should also be removed. This includes any empty/unused UIApplicationDelegate methods.
Preferred:
overridefunc tableView(_ tableView:UITableView, numberOfRowsInSection section:Int)->Int{returnDatabase.contacts.count}
Not Preferred:
overridefunc didReceiveMemoryWarning(){ super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated.}overridefunc numberOfSections(in tableView:UITableView)->Int{ // #warning Incomplete implementation, return the number of sectionsreturn1}overridefunc tableView(_ tableView:UITableView, numberOfRowsInSection section:Int)->Int{ // #warning Incomplete implementation, return the number of rowsreturnDatabase.contacts.count}
Import only the modules a source file requires. For example, don't importUIKit
when importingFoundation
will suffice. Likewise, don't importFoundation
if you must importUIKit
.
Preferred:
import UIKitvar view: UIViewvar deviceModels: [String]
Preferred:
import Foundationvar deviceModels: [String]
Not Preferred:
import UIKitimport Foundationvar view: UIViewvar deviceModels: [String]
Not Preferred:
import UIKitvar deviceModels: [String]
- Indent using4 spaces rather than tabs to conserve space and help prevent line wrapping. Check xcode settings at the end.
- Method braces and other braces (
if
/else
/switch
/while
etc.) always open on the same line as the statement but close on a new line.
Pro Tip: You can re-indent by selecting some code (orCommand-A to select all) and thenControl-I (orEditor ▸ Structure ▸ Re-Indent in the menu). Some of the Xcode template code will have 4-space tabs hard coded, so this is a good way to fix that.
Preferred:
if user.isHappy{ // Do something}else{ // Do something else}
Not Preferred:
if user.isHappy{ // Do something}else{ // Do something else}
There should be exactly one blank line between methods to aid in visual clarity and organization. Whitespace within methods should separate functionality, but having too many sections in a method often means you should refactor into several methods.
There should always be a blank lines after an opening brace but none before a closing brace.
Colons always have no space on the left and one space on the right. Exceptions are the ternary operator
? :
, empty dictionary[:]
and#selector
syntaxaddTarget(_:action:)
.
Preferred:
classTestDatabase:Database{vardata:[String:CGFloat]=["A":1.2,"B":3.2]}
Not Preferred:
classTestDatabase:Database{vardata:[String:CGFloat]=["A":1.2,"B":3.2,"C":2.2]}
- There should be exactly one blank line after each function's declaration before any code. Exceptions are one-line functions that can be inlined, and invoking the
super
of the current method.
Preferred:
func reticulateSplines(_ splines:[Double])->Bool{ // reticulate code goes here}func reticulateSplines(_ splines:[Double])->Bool{ /* one-line reticulate code goes here */}func reticulateSplines(_ splines:[Double])->Bool{ super.reticulateSplines(splines) // reticulate code goes here}
Not Preferred:
func reticulateSplines(_ splines:[Double])->Bool{ // reticulate code goes here}func reticulateSplines(_ splines:[Double])->Bool{ super.reticulateSplines(splines) // reticulate code goes here}
Long lines should be wrapped at120 characters.
Remove any trailing whitespaces at the ends of lines.
Add a single newline character at the end of each file.
When they are needed, use comments to explainwhy a particular piece of code does something. Comments must be kept up-to-date or deleted.
Avoid block comments inline with code, as the code should be as self-documenting as possible.Exception: This does not apply to those comments used to generate documentation.
Avoid the use of C-style comments (/* ... */
). Prefer the use of double- or triple-slash.
When documenting code, prefer the triple slash documentation style///
.
Prefer one single- Parameters:
section with bullet points for each parameter to multipleparameter name:
sections.
Add an empty line between the description and parameters.
Try to take advantage of existing keywords (e.g.Returns
,Throws
,Warning
,Attention
...), code ( single line`<code>`
or```<multiline code>```
and overall markdown formatting to provide as much information and details as possible.
Preferred:
/// Reticulates some splines using a given adjustment factor `ƒ` and translation constant `∂`.////// - Parameters:/// - spline: The spline to perform reticulation on./// - adjustmentFactor: The reticulation factor `ƒ`./// - translateConstant: The translation constant `∂`./// - comment: The reticulation operation comment, for logging purposes./// - Returns: A flag indicating if reticulation was successful.func reticulateSplines( _ splines:[Double], adjustmentFactor:Double, translateConstant:Int, comment:String)->Bool{...}
Not Preferred:
/** Reticulates some splines using a given adjustment factor `ƒ` and translation constant `∂`. - parameter spline: The spline to perform reticulation on. - parameter adjustmentFactor: The reticulation factor `ƒ`. - parameter translateConstant: The translation constant `∂`. - parameter comment: The reticulation operation comment, for logging purposes. - returns: A flag indicating if reticulation was successful.*/func reticulateSplines( _ splines:[Double], adjustmentFactor:Double, translateConstant:Int, comment:String)->Bool{...}
Remember, structs havevalue semantics. Use structs for things that do not have an identity. An array that contains [a, b, c] is really the same as another array that contains [a, b, c] and they are completely interchangeable. It doesn't matter whether you use the first array or the second, because they represent the exact same thing. That's why arrays are structs.
Classes havereference semantics. Use classes for things that do have an identity or a specific life cycle. You would model a person as a class because two person objects are two different things. Just because two people have the same name and birthdate, doesn't mean they are the same person. But the person's birthdate would be a struct because a date of 3 March 1950 is the same as any other date object for 3 March 1950. The date itself doesn't have an identity.
Sometimes, things should be structs but need to conform toAnyObject
or are historically modeled as classes already (NSDate
,NSSet
). Try to follow these guidelines as closely as possible.
Here's an example of a well-styled class definition:
classCircle:Shape{varx:Int,y:Intvarradius:Doublevardiameter:Double{get{ radius*2}set{ radius= newValue/2}}init(x:Int, y:Int, radius:Double){self.x= xself.y= yself.radius= radius}convenienceinit(x:Int, y:Int, diameter:Double){self.init(x: x, y: y, radius: diameter/2)}overridefunc area()->Double{Double.pi* radius* radius}}extensionCircle:CustomStringConvertible{vardescription:String{"center =\(centerString) area =\(area())"}privatevarcenterString:String{"(\(x),\(y))"}}
The example above demonstrates the following style guidelines:
- Specify types for properties, variables, constants, argument declarations and other statements with a space after the colon but not before, e.g.
x: Int
, andCircle: Shape
. - Define multiple variables and structures on a single line if they share a common purpose / context.
- Indent getter and setter definitions and property observers.
- Don't add modifiers such as
internal
when they're already the default. Similarly, don't repeat the access modifier when overriding a method. - Organize extra functionality (e.g. printing) in extensions.
- Hide non-shared, implementation details such as
centerString
inside the extension usingprivate
access control. - Take advantage of Swift 5.1's implicit
return
in one line closures.
For conciseness, avoid usingself
since Swift does not require it to access an object's properties or invoke its methods.
Useself
only when required by the compiler (e.g. in@escaping
closures) or insideinit
's when initializing each property (i.e. not just to disambiguate properties from arguments, but onall of them).
For conciseness, if a computed property is read-only, omit the get clause. The get clause is required only when a set clause is provided.
If possible, take advantage of Swift 5.1's implicitreturn
in one line closures, and put the closure body inline with the property declaration.
Preferred:
vardiameter:Double{ radius*2}
Not Preferred:
vardiameter:Double{get{return radius*2}}
Sometimes we need to expose some members like properties and functions publicly (e.g. for read-only property), but have ashadowing version for private usage (e.g. read-write property).
When shadowing a property, the private property's nameshould be prefixed with a
_
, instead of more verbose alternatives likemutatingX
, etc..When shadowing a function, the private function's namecan be prefixed with a
_
, in the lack of a more well suited name to define it.
Preferred:
varstate:Int{ _state}privatevar_state:IntletdynamicState:Property<Int>privatelet_dynamicState:MutableProperty<Int>func reticulateSplines(_ splines:[String])...privatefunc _reticulateSplines(_ splines:[String], configuration:Configuration)func sort(numbers:[Int])...privatefunc mergeSort(numbers:[String], parameters:Parameters)
Not Preferred:
varstate:Int{ internalState}privatevarinternalState:IntletdynamicState:Property<Int>privateletmutableDynamicState:MutableProperty<Int>func reticulateSplines(_ splines:[String])...privatefunc reticulateSplinesHelper(splines:[String], configuration:Configuration)func sort(numbers:[Int])...privatefunc calculateSort(numbers:[String], parameters:Parameters)
Use offinal
is advised, it helps to clarify your intention with the class and it's worth the cost.
- In classes when it is not suppose to be subclassed.
- In members when it is a
lazy var
that is not supposed to be changed in runtime. - Do not use in
let
variables.
In the below example,Box
has a particular purpose and customization in a derived class is not intended. Marking itfinal
makes that clear.
// Turn any generic type into a reference type using this Box class.finalclassBox<T>{letvalue:Tinit(_ value:T){self.value= value}}
When defining a generic type, prefer inlining the generic declaration and constraints whenever possible. If not possible, break it according to the following rules:
- move the
where
clause to a separate line, if it doesn't fit inline.- break the conditions in the
where
clause to separate lines if they don't fit into a single line.
- break the conditions in the
- break the generic declaration
<>
into separate lines, by adding a line break after the initial<
, then putting each type in its own line with an extra indentation, and "closing" the generic with a>:
in its own line, aligned with the initial declaration. - When the generic declaration is broken into multiple lines, each conformance/subclassing should be put on a separate line as well.
finalclassMyAwesomeType< SomeGeneric, AnotherGeneric, YetAnotherGeneric>:MyProtocol,SomeOtherProtocol,YetAnotherProtocol,NamingIsHardSoSometimesWeNeedVeryLargeNamesInAProtocolwhere SomeGeneric:Some&Nice&Composable&Protocols, AnotherGeneric.SubType==SomeOtherType, YetAnotherGeneric.YetAnotherSubType==YetAnotherType{letmyProperty:Boolfunc init(){}}
When defining a typealias, prefer inlining its declaration and constraints whenever possible. If not possible, break it according to the following rules:
- move the
where
clause to a separate line if it doesn't fit inline, indenting it an additional level.- break the conditions in the
where
clause to separate lines if they don't fit into a single line.
- break the conditions in the
- move the type being aliased to the next line if it doesn't fit inline, indenting it an additional level.
- break the generic declaration
<>
of the type beind aliased into separate lines, by adding a line break after the initial<
, then putting each type in its own line with an extra indentation, and "closing" the generic with a>
in its own line, aligned with the aliased type's declaration.
typealiasSomeSimpleTypealias=SomeType<SomeGeneric>typealiasSomeGenericTypealias<SomeGeneric>=SomeOtherType<SomeGeneric> where SomeGeneric: SomeProtocoltypealiasSomeOtherGenericTypealias<SomeGeneric>=YetAnotherType<SomeGeneric> where SomeGeneric: SomeProtocol& And& A& Bunch& Of& OtherstypealiasSomeOtherGenericTypealias<SomeGeneric>=YetAnotherType<SomeGeneric> whereSomeGeneric: SomeProtocol& And& A& Bunch& Of& Others,SomeGeneric.InternalType== SomeOtherTypetypealiasMyVeryLargeTypeAlias=MyVeryLongNamedGenericType<SomeGeneric<WhySoManyGenericTypes,IAmSureThereMustBeAnEasierWay,IGuessSometimesWeJustHaveLotsOfComplexAbstractions,>,SomeOtherGeneric>typealiasMyLargeTypeAlias=SomeOtherVeyLongNamedGenericType<ThatHasItsOwnGenericType<WhichItselfHasAnotherGenericType>>typealiasYetAnotherGenericTypealias<AnotherGeneric>=YetAnotherVeryLongNamedGenericType<AnotherGeneric> whereAnotherGeneric: AnotherProtocol& And& His& FriendsAnotherGeneric.SuperImportantType== YetAnotherType
When declaring a function al
Keep short function declarations on one line including the opening brace:
func reticulateSplines(_ splines:[Double])->Bool{ // reticulate code goes here}
For functions with long signatures, put each parameter on a new line and add an extra indent on subsequent lines:
func reticulateSplines( _ splines:[Double], adjustmentFactor:Double, translateConstant:Int, comment:String)->Bool{ // reticulate code goes here}
Note: We can use Xcode automatic alignment by pressing return before each parameter.Don't use(Void)
to represent the lack of an input; simply use()
. UseVoid
instead of()
for closure and function outputs, and omitVoid
return type on function declarations.
Preferred:
func updateConstraints(){ // magic happens here}typealiasCompletionHandler=(result)->Void
Not Preferred:
func updateConstraints()->(){ // magic happens here}func updateConstraints()->Void{ // magic happens here}typealiasCompletionHandler=(result)->()
Mirror the style of function declarations at call sites. Calls that fit on a single line should be written as such:
letsuccess=reticulateSplines(splines)
If the call site must be wrapped, put each parameter on a new line, indented one additional level with the closing brace on a line of its own:
letsuccess=reticulateSplines( _ splines: splines, adjustmentFactor:1.3, translateConstant:2, comment:"normalize the display")
Use trailing closure syntax only if there's a single closure expression parameter at the end of the argument list. Give the closure parameters descriptive names.
Preferred:
UIView.animate(withDuration:1.0){self.myView.alpha=0}UIView.animate( withDuration:1.0, animations:{self.myView.alpha=0}, completion:{ finishedinself.myView.removeFromSuperview()})UIView.animate( withDuration:1.0, animations:{self.myView.alpha=0...}, completion:{ finishedinself.myView.removeFromSuperview()...})
Not Preferred:
UIView.animate(withDuration:1.0, animations:{self.myView.alpha=0})UIView.animate(withDuration:1.0, animations:{self.myView.alpha=0}){ finself.myView.removeFromSuperview()}
For single-expression closures where the context is clear, use implicit returns:
attendeeList.sort{ $0> $1}attendeeList.sort{ first, secondin first> second}
Chained methods using trailing closures should be clear and easy to read in context. Decisions on spacing, line breaks, and when to use named versus anonymous arguments is left to the discretion of the developer. Examples:
letvalue= numbers.map{ $0*2}.filter{ $0%3==0}.index(of:90)letvalue= numbers.map{$0*2}.filter{$0>50}.map{$0+10}
Always use Swift's native types and expressions when available. Swift offers bridging to Objective-C so you can still use the full set of methods as needed.
Preferred:
letwidth=120.0 // DoubleletwidthString="\(width)" // String
Less Preferred:
letwidth=120.0 // DoubleletwidthString=(widthasNSNumber).stringValue // String
Not Preferred:
letwidth:NSNumber=120.0 // NSNumberletwidthString:NSString= width.stringValue // NSString
In drawing code, useCGFloat
if it makes the code more succinct by avoiding too many conversions.
Constants are defined using thelet
keyword and variables with thevar
keyword. Always uselet
instead ofvar
if the value of the variable will not change.
Pro Tip: A good technique is to define everything usinglet
and only change it tovar
if the compiler complains!
You can define constants on a type rather than on an instance of that type using type properties. To declare a type property as a constant simply usestatic let
. Type properties declared in this way are generally preferred over global constants because they are easier to distinguish from instance properties. Example:
Preferred:
enumMath{staticlete=2.718281828459045235360287staticletroot2=1.41421356237309504880168872}lethypotenuse= side* Math.root2
Pro Tip: The advantage of using a case-lessenum
is that it can't accidentally be instantiated and works as a pure namespace.
Not Preferred:
lete=2.718281828459045235360287 // pollutes global namespaceletroot2=1.41421356237309504880168872lethypotenuse= side* root2 // what is root2?
Static methods and type properties work similarly to global functions and global variables and should be used sparingly. They are useful when functionality is scoped to a particular type or when Objective-C interoperability is required.
Declare variables and function return types as optional with?
where anil
value is acceptable.
Avoid the usage of implicitly unwrapped optionals (declared with!
), except on unit tests and when dealing with storyboard outlets. Prefer optional binding to implicitly unwrapped optionals in all other cases.
When accessing an optional value, use optional chaining if the value is only accessed once or if there are many optionals in the chain:
textContainer?.textLabel?.setNeedsDisplay()
Use optional binding when it's more convenient to unwrap once and perform multiple operations:
iflet textContainer= textContainer{ // do many things with textContainer}
If the optional value is required to the context, useguard let ...
withassertionFailure
to catch the problem in debug time orfatalError
if the execution cannot continue.
When naming optional variables and properties, avoid naming them likeoptionalString
ormaybeView
since their optional-ness is already in the type declaration.
For optional binding, shadow the original name whenever possible rather than using names likeunwrappedView
oractualLabel
.
Preferred:
varsubview:UIView?varvolume:Double?// later on...iflet subview= subview,let volume= volume{ // do something with unwrapped subview and volume}// another exampleUIView.animate(withDuration:2.0){[weak self]inguardlet self=selfelse{return}self.alpha=1.0}
Not Preferred:
varoptionalSubview:UIView?varvolume:Double?iflet unwrappedSubview= optionalSubview{iflet realVolume= volume{ // do something with unwrappedSubview and realVolume}}// another exampleUIView.animate(withDuration:2.0){[weak self]inguardlet strongSelf=selfelse{return} strongSelf.alpha=1.0}
Consider using lazy initialization for finer grained control over object lifetime. This is especially true forUIViewController
that loads views lazily. You can either use a closure that is immediately called{ }()
or call a private factory method. Example:
lazyvarlocationManager=makeLocationManager()privatefunc makeLocationManager()->CLLocationManager{letmanager=CLLocationManager() manager.desiredAccuracy= kCLLocationAccuracyBest manager.delegate=self manager.requestAlwaysAuthorization()return manager}
Notes:
[unowned self]
is not required here. A retain cycle is not created.- Location manager has a side-effect for popping up UI to ask the user for permission so fine grain control makes sense here.
Prefer compact code and let the compiler infer the type for constants or variables of single instances. Type inference is also appropriate for small, non-empty arrays and dictionaries. When required, specify the specific type such asCGFloat
orInt16
.
Preferred:
letmessage="Click the button"letcurrentBounds=computeViewBounds()varnames=["Mic","Sam","Christine"]letmaximumWidth:CGFloat=106.5
Not Preferred:
letmessage:String="Click the button"letcurrentBounds:CGRect=computeViewBounds()varnames=[String]()
For empty arrays and dictionaries, use type annotation. (For an array or dictionary assigned to a large, multi-line literal, use type annotation.)
Preferred:
varnames:[String]=[]varlookup:[String:Int]=[:]
Not Preferred:
varnames=[String]()varlookup=[String: Int]()
NOTE: Following this guideline means picking descriptive names is even more important than before.
Prefer the shortcut versions of type declarations over the full generics syntax.
Preferred:
vardeviceModels:[String]varemployees:[Int:String]varfaxNumber:Int?
Not Preferred:
vardeviceModels:Array<String>varemployees:Dictionary<Int,String>varfaxNumber:Optional<Int>
Free functions, which aren't attached to a class or type, should be used sparingly. When possible, prefer to use a method instead of a free function. This aids in readability and discoverability.
Free functions are most appropriate when they aren't associated with any particular type or instance.
Preferred
letsorted= items.mergeSorted() // easily discoverablerocket.launch() // acts on the model
Not Preferred
letsorted=mergeSort(items) // hard to discoverlaunch(&rocket)
Free Function Exceptions
lettuples=zip(a, b) // feels natural as a free function (symmetry)letvalue=max(x, y, z) // another free function that feels natural
Code should not create reference cycles. Analyze your object graph and prevent strong cycles withweak
andunowned
references. Alternatively, use value types (struct
,enum
) to prevent cycles altogether.
Extend object lifetime using the[weak self]
andguard let self = self else { return }
idiom.[weak self]
is preferred to[unowned self]
where it is not immediately obvious thatself
outlives the closure. Explicitly extending lifetime is preferred to optional chaining.
Preferred
resource.request().onComplete{[weak self] responseinguardlet self=selfelse{return}letmodel=self.updateModel(response)self.updateUI(model)}
Not Preferred
// might crash if self is released before response returnsresource.request().onComplete{[unowned self] responseinletmodel=self.updateModel(response)self.updateUI(model)}
Not Preferred
// deallocate could happen between updating the model and updating UIresource.request().onComplete{[weak self] responseinletmodel=self?.updateModel(response)self?.updateUI(model)}
Not Preferred
// This has been confirmed as a compiler hack and should be avoidedresource.request().onComplete{[weak self] responseinguardlet `self`=selfelse{return}letmodel=self.updateModel(response)self.updateUI(model)}
Not Preferred
// Lacks consistency and makes the codebase harder to reason aboutresource.request().onComplete{[weak self] responseinguardlet strongSelf=selfelse{return}letmodel= strongSelf.updateModel(response) strongSelf.updateUI(model)}
- Using
private
andfileprivate
appropriately, adds clarity and promotes encapsulation. - Prefer
private
tofileprivate
when possible. Using extensions may require you to usefileprivate
.
Only explicitly useopen
,public
, andinternal
when you require a full access control specification.
Use access control as the leading property specifier. The only things that should come before access control are thestatic
specifier or attributes such as@IBAction
,@IBOutlet
and@discardableResult
.
Preferred:
privateletmessage="Great Scott!"classTimeMachine{privatedynamic lazyvarfluxCapacitor=FluxCapacitor()}
Not Preferred:
fileprivateletmessage="Great Scott!"classTimeMachine{ lazydynamicprivatevarfluxCapacitor=FluxCapacitor()}
- Attributes such as
@IBAction
,@IBOutlet
,@discardableResult
,@objc
, etc should be placed in the lineabove the declaration and stacked vertically, and not inline. - The only exception to this is
@unknown default:
inswitch
statements.
Preferred:
@objc(MNDTimeMachine)classTimeMachine:NSObject{@available(*, unavailable)privatedynamic lazyvarfluxCapacitor=FluxCapacitor()@discardableResult@objcfunc calculateFlux()->Flux}
Not Preferred:
@objc(MNDTimeMachine)classTimeMachine:NSObject{@available(*, unavailable) lazydynamicprivatevarfluxCapacitor=FluxCapacitor()@discarcableResult@objcfunc calculateFlux()->Flux}
Prefer thefor-in
style offor
loop over thewhile-condition-increment
style.
Preferred:
for_in0..<3{print("Hello three times")}for(index, person)in attendeeList.enumerated(){print("\(person) is at position #\(index)")}forindexinstride(from:0, to: items.count, by:2){print(index)}forindexin(0...3).reversed(){print(index)}
Not Preferred:
vari=0while i<3{print("Hello three times") i+=1}vari=0while i< attendeeList.count{letperson=attendeeList[i]print("\(person) is at position #\(i)") i+=1}
The Ternary operator,?:
, should only be used when it increases clarity or code neatness. A single condition is usually all that should be evaluated. Evaluating multiple conditions is usually more understandable as anif
statement or refactored into instance variables. In general, the best use of the ternary operator is during assignment of a variable and deciding which value to use.
For large expressions, break the ternary operator into multiple lines, with the?
and:
expressions each in its own line.
Preferred:
letvalue=5result= value!=0? x: yletisHorizontal=trueresult= isHorizontal? x: yletisHorizontal=trueresult= isHorizontal?mySuperComplexExpression(z):someOtherComplexExpression(w)
Not Preferred:
result= a> b? x= c> d? c: d: y
When usingswitch
, please try to adopt the following rules:
- Add a newline between each
case
block inswitch
statements if at least one spans more than one line. - Always place every
case
body in its own separate line, with an extra indentation. - When multiple conditions/patterns are defined in a single
case
, prefer putting each one in its own line to ease redability and make diffs nicer upon changes. - Capture associated values in
enum
's (e.g.var
orlet
) at avalue level and not at acase level. - Try to place the
where
clause inline with the respectivecase
, and if not possible move it to the next line, at the same indentation.- If compounding multiple predicates in the
where
clause, use,
instead of explicit&&
's.
- If compounding multiple predicates in the
- Prefer explicitly handling all cases instead of using a
default
case.
Preferred:
switch value{case.first: // some magiccase.second: // alternative magiccase.third: // ultimate magic}switch anotherValue{case.potato(let kg):print("🥔 weights\(kg)Kg's")case.banana(let g),.apple(let g),.watermelon(let g):print("🍌|🍏|🍉 weights\(g)g's")addFruitToSalad()case.eggs(let number,let size)where size==.large,someLongFunctionThatTakesUpALotOfSpaceAndValidatesNumber(number):print("🥚 amount of Large eggs that passed the test:\(number)")case.eggs(let number,let size):print("🥚 amount to\(number) of size\(size)")}
Not Preferred:
switch value{case.first: // some magiccase.second: // alternative magiccase.third: // ultimate magic}switch anotherValue{caselet.potato(kg):print("🥔 weights\(kg)Kg's")case.banana(let g),.apple(let g),.watermelon(let g):print("🍌|🍏|🍉 weights\(g)g's")addFruitToSalad()caselet.eggs(number, size)where size==.large &&someLongFunctionThatTakesUpALotOfSpaceAndValidatesNumber(number):print("🥚 amount to\(number) of size\(size)")default:print("🤷♂️ Got some food which *should be™* eggs:\(anotherValue)")}
When the presence of an optional value is required to the context (but not the value itself, i.e., it won't be used), perform a boolean test instead of using optional binding inif
orguard
statements. Prefer!= nil
overlet _ =
.
Preferred:
guard optionalController!=nilelse{return}// do something that requires optionalController but does not use it// another exampleif optionalView!=nil{ // do something that requires optionalView but does not use it}else{ // do something that does not require optionalView}
Not Preferred:
guardlet _= optionalControllerelse{return}// do something that requires optionalController but does not use it// another exampleiflet _= optionalView{ // do something that requires optionalView but does not use it}else{ // do something that does not require optionalView}
When coding with conditionals, the left-hand margin of the code should be the "golden" or "happy" path. That is, don't nestif
statements. Multiple return statements are OK. Theguard
statement is built for this.
Preferred:
func computeFFT(context:Context?, inputData:InputData?)throws->Frequencies{guardlet context= contextelse{throwFFTError.noContext}guardlet inputData= inputDataelse{throwFFTError.noInputData} // use context and input to compute the frequenciesreturn frequencies}
Not Preferred:
func computeFFT(context:Context?, inputData:InputData?)throws->Frequencies{iflet context= context{iflet inputData= inputData{ // use context and input to compute the frequenciesreturn frequencies}else{throwFFTError.noInputData}}else{throwFFTError.noContext}}
When multiple optionals are unwrapped either withguard
orif let
(same applies to multiple conditions), minimize nesting by using the compound version when possible. In the compound version, place theguard
on its own line, then ident each condition on its own line. Theelse
clause is indented to match theguard
and the code is indented to match the conditions, as shown below. Example:
Preferred:
guardlet number1= number1,let number2= number2,let number3= number3else{fatalError("impossible")}// do something with numbers
Not Preferred:
iflet number1= number1{iflet number2= number2{iflet number3= number3{ // do something with numbers}else{fatalError("impossible")}}else{fatalError("impossible")}}else{fatalError("impossible")}
Guard statements are required to exit in some way. Generally, this should be simple one line statement such asreturn
,throw
,break
,continue
, andfatalError()
. Large code blocks should be avoided. If cleanup code is required for multiple exit points, consider using adefer
block to avoid cleanup code duplication.
If possible, place the exit closure inline with theguard
, otherwise in a new line:
Preferred:
guardlet number= numberelse{fatalError("impossible")}// do something with number
guardlet number= numberelse{...fatalError("impossible")}// do something with number
Not Preferred:
guardlet number= numberelse{fatalError("impossible")}// do something with number
guardlet number= numberelse{fatalError("impossible")}// do something with number
guardlet number1= number1,let number2= number2,let number3= number3else{fatalError("impossible")}// do something with numbers
Swift does not require a semicolon after each statement in your code. They are only required if you wish to combine multiple statements on a single line.
Do not write multiple statements on a single line separated with semicolons.
Preferred:
letswift="not a scripting language"
Not Preferred:
letswift="not a scripting language";
NOTE: Swift is very different from JavaScript, where omitting semicolons isgenerally considered unsafe
Parentheses around conditionals are not required and should be omitted.
Preferred:
if name=="Hello"{print("World")}
Not Preferred:
if(name=="Hello"){print("World")}
In larger expressions, optional parentheses can sometimes make code read more clearly.
Preferred:
letplayerMark=(player== current?"X":"O")
When building a long string literal, you're encouraged to use the multi-line string literal syntax. Open the literal on the same line as the assignment but do not include text on that line. Indent the text block one additional level.
Preferred:
letmessage=""" You cannot charge the flux\ capacitor with a 9V battery. You must use a super-charger\ which costs 10 credits. You currently\ have\(credits) credits available."""
Not Preferred:
letmessage="""You cannot charge the flux\ capacitor with a 9V battery. You must use a super-charger\ which costs 10 credits. You currently\ have\(credits) credits available."""
Not Preferred:
letmessage="You cannot charge the flux"+"capacitor with a 9V battery.\n"+"You must use a super-charger"+"which costs 10 credits. You currently"+"have\(credits) credits available."
When declaring a string that would require a significant amount of escaping, such as regular expressions, prefer usingraw strings.
Preferred:
letjson=#"{"email":"banana@banana.com","salutation":"Sir"}"#letregex=#"(?!(1st|2nd|3rd|\d{1,2}th)\s).*between \d{1,2}-\d{1,2}(am|pm)"#
Not Preferred:
letjson="{\"email\":\"banana@banana.com\",\"salutation\":\"Sir\"}"letregex="(?!(1st|2nd|3rd|\\d{1,2}th)\\s).*between\\d{1,2}-\\d{1,2}(am|pm)"
In the Xcode project, the organization should be set toMindera
or to the client's name if required.
The Bundle Identifier should be set tocom.mindera.client.projectName
whereclient
is the client company name andproject
is the name of the project we are working on.This will make sure that the app bundle identifier will not collide with other applications bundle identifier.
Example: We should not deploy applications into the Mindera account with the bundle identifiercom.client.projectName
About
The "official" Swift style guide for Mindera ❤️
Topics
Resources
License
Uh oh!
There was an error while loading.Please reload this page.