Repository: kodecocodes/swift-style-guide Branch: main Commit: e6d4eda9b00f Files: 6 Total size: 54.1 KB Directory structure: gitextract_ekwe1c7p/ ├── CONTRIBUTING.markdown ├── CREDITS.markdown ├── LICENSE.txt ├── README.markdown ├── SWIFTLINT.markdown └── com.raywenderlich.swiftlint.yml ================================================ FILE CONTENTS ================================================ ================================================ FILE: CONTRIBUTING.markdown ================================================ # Contributing to the Official raywenderlich.com Swift Style Guide. This style guide is a living document that evolves with the Swift language. It is different from others you may see, because the focus is centered on readability for print and the web. We created this style guide to keep the code in our books, tutorials, and starter kits nice and consistent — even though we have many different authors working on the books. We appreciate and encourage contributions from the community that improve this document and hence the quality of tutorials we produce. This document outlines the process for making contributions to the guide. **Note:** You are responsible for adding your name to the list of contributors should you desire. ## Fixing Typos Uncontroversial, non-additive changes such as misspellings, grammar or compiler errors can be fixed by simply issuing a pull request to master. The maintainer will merge the pull request or, if it is deemed "controversial" request the contributor open an issue so that other members of the community can participate in the discussion. ## Style Changes Authors at RayWenderlich.com are expected to follow all of the rules in this style guide unless special circumstances apply. Because of this, it is important that updates happen at predictable times. Be aware in advance that there may be a significant delay (many months) before a suggestion is ratified on the master branch. ### Step 1: Open an Issue Open an issue on github and describe the change you would like to see or rule that you would like to have added. You can even propose the exact change in github markdown which can be pasted into the guide. ### Step 2: Wait for Community Feedback Wait for feedback on the issue. Even if the feedback is negative, don't close the issue too quickly. Often times the discussion itself can be useful and give way to something even better. Style guides are very subjective and it is important to always be respectful. We expect participants to follow the same community guidelines as the Swift project itself outlined at [contributor-covenant.org](https://contributor-covenant.org) ### Step 3: Wait for Maintainer Go Ahead The maintainer will decide if a change is go or no go. This decision is not necessarily based on the feedback of the community, but will often play a role. If you believe that the maintainer is mistaken, you can appeal the decision by just asking them. At this point the maintainer will poll the RayWenderlich team leads for a final decision with RayWenderlich acting as tie breaker if required. Apologies in advance if your style suggestion isn't accepted. You are always welcome, however, to make your own style guide for your organization or community! ### Step 4: Create a Pull Request on the Update branch Given the go ahead from the maintainer, create a pull request on the update branch in the repo. There should be one of these. If it is not clear what it is, ask the maintainer. The current update branch is `update.` ### Step 5: Branch Merged At this point your involvement is complete. The maintainer will merge your PR to the update branch. ### Step 6: Update Branch Reviewed The RayWenderlich.com team has a chance to look at the final updated document before it is merged to master. If an objection is raised, as with the appeal process, teams leads will deliberate on the final decision. ### Step 7: Update Branch Merged to Master Hurray! ================================================ FILE: CREDITS.markdown ================================================ ## Credits [Richard Critz](https://github.com/rcritz) currently maintains this style guide. It is a collaborative effort from the most stylish raywenderlich.com team members and its community: * [Jawwad Ahmad](https://github.com/jawwad) * [Soheil Moayedi Azarpour](https://github.com/moayes) * [Scott Berrevoets](https://github.com/Scott90) * [Jessy Catterwaul](https://github.com/JessyCatterwaul) * [Eric Cerney](https://github.com/ecerney) * [Sam Davies](https://github.com/sammyd) * [Evan Dekhayser](https://github.com/edekhayser) * [Jean-Pierre Distler](https://github.com/pdistler) * [Colin Eberhardt](https://github.com/ColinEberhardt) * [Vadim Eisenberg](https://github.com/vadimeisenbergibm) * [Ray Fix](https://github.com/rayfix) * [Joshua Greene](https://github.com/JRG-Developer) * [Robert Gummesson](https://github.com/RobertGummesson) * [Greg Heo](https://github.com/gregheo) * [Matthijs Hollemans](https://github.com/hollance) * [Erik Kerber](https://github.com/eskerber) * [Christopher LaPollo](https://github.com/elephantronic) * [Ben Morrow](https://github.com/benmorrow) * [Andy Pereira](https://github.com/macandyp) * [Ryan Nystrom](https://github.com/rnystrom) * [Andy Obusek](https://github.com/obuseme) * [Cesare Rocchi](https://github.com/funkyboy) * [Ellen Shapiro](https://github.com/designatednerd) * [Marin Todorov](https://github.com/icanzilb) * [Chris Wagner](https://github.com/cwagdev) * [Ray Wenderlich](https://github.com/rwenderlich) * [Jack Wu](https://github.com/jackwu95) * [Richard Critz](https://github.com/rcritz) Hat tip to [Nicholas Waynik](https://github.com/ndubbs) and the [Objective-C Style Guide](https://github.com/raywenderlich/objective-c-style-guide) team! ================================================ FILE: LICENSE.txt ================================================ This style guide is available under the MIT license: Copyright (c) 2024 Kodeco Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: README.markdown ================================================ # The Official Kodeco Swift Style Guide. ### Updated for Swift 5 This style guide is different from others you may see, because the focus is centered on readability for print and the web. We created this style guide to keep the code in our books, tutorials, and starter kits nice and consistent — even though we have many different authors working on the books. Our overarching goals are clarity, consistency and brevity, in that order. ## Table of Contents * [Correctness](#correctness) * [Using SwiftLint](#using-swiftlint) * [Naming](#naming) * [Prose](#prose) * [Delegates](#delegates) * [Use Type Inferred Context](#use-type-inferred-context) * [Generics](#generics) * [Class Prefixes](#class-prefixes) * [Language](#language) * [Code Organization](#code-organization) * [Protocol Conformance](#protocol-conformance) * [Unused Code](#unused-code) * [Minimal Imports](#minimal-imports) * [Spacing](#spacing) * [Comments](#comments) * [Classes and Structures](#classes-and-structures) * [Use of Self](#use-of-self) * [Protocol Conformance](#protocol-conformance) * [Computed Properties](#computed-properties) * [Final](#final) * [Function Declarations](#function-declarations) * [Function Calls](#function-calls) * [Closure Expressions](#closure-expressions) * [Types](#types) * [Constants](#constants) * [Static Methods and Variable Type Properties](#static-methods-and-variable-type-properties) * [Optionals](#optionals) * [Lazy Initialization](#lazy-initialization) * [Type Inference](#type-inference) * [Syntactic Sugar](#syntactic-sugar) * [Functions vs Methods](#functions-vs-methods) * [Memory Management](#memory-management) * [Extending Object Lifetime](#extending-object-lifetime) * [Access Control](#access-control) * [Control Flow](#control-flow) * [Ternary Operator](#ternary-operator) * [Golden Path](#golden-path) * [Failing Guards](#failing-guards) * [Semicolons](#semicolons) * [Parentheses](#parentheses) * [Multi-line String Literals](#multi-line-string-literals) * [No Emoji](#no-emoji) * [No #imageLiteral or #colorLiteral](#no-imageliteral-or-colorliteral) * [Organization and Bundle Identifier](#organization-and-bundle-identifier) * [Copyright Statement](#copyright-statement) * [Smiley Face](#smiley-face) * [References](#references) ## Correctness Strive to make your code compile without warnings. This rule informs many style decisions such as using `#selector` types instead of string literals. ## Using SwiftLint When writing for Kodeco, you are strongly encouraged — perhaps even required, depending on your team — to use our SwiftLint configuration. See the [SwiftLint Policy](SWIFTLINT.markdown) for more information. ## Naming Descriptive and consistent naming makes software easier to read and understand. Use the Swift naming conventions described in the [API Design Guidelines](https://swift.org/documentation/api-design-guidelines/). Some key takeaways include: - striving for clarity at the call site - prioritizing clarity over brevity - using `camelCase` (not `snake_case`) - using `UpperCamelCase` for types and protocols, `lowerCamelCase` 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 describe _what something is_ should read as nouns - protocols that describe _a 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 ### Prose When referring to methods in prose, being unambiguous is critical. To refer to a method name, use the simplest form possible. 1. Write the method name with no parameters. **Example:** Next, you need to call `addTarget`. 2. Write the method name with argument labels. **Example:** Next, you need to call `addTarget(_:action:)`. 3. Write the full method name with argument labels and types. **Example:** Next, you need to call `addTarget(_: Any?, action: Selector?)`. For the above example using `UIGestureRecognizer`, 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 press **Shift-Control-Option-Command-C** (all 4 modifier keys) and Xcode will kindly put the signature on your clipboard. ![Methods in Xcode jump bar](screens/xcode-jump-bar.png) ### Class Prefixes Swift types are automatically namespaced by the module that contains them and you should not add a class prefix such as RW. 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. ```swift import SomeModule let myClass = MyModule.UsefulClass() ``` ### Delegates When creating custom delegate methods, an unnamed first parameter should be the delegate source. (UIKit contains numerous examples of this.) **Preferred**: ```swift func namePickerView(_ namePickerView: NamePickerView, didSelectName name: String) func namePickerViewShouldReload(_ namePickerView: NamePickerView) -> Bool ``` **Not Preferred**: ```swift func didSelectName(namePicker: NamePickerViewController, name: String) func namePickerShouldReload() -> Bool ``` ### Use Type Inferred Context Use compiler inferred context to write shorter, clear code. (Also see [Type Inference](#type-inference).) **Preferred**: ```swift let selector = #selector(viewDidLoad) view.backgroundColor = .red let toView = context.view(forKey: .to) let view = UIView(frame: .zero) ``` **Not Preferred**: ```swift let selector = #selector(ViewController.viewDidLoad) view.backgroundColor = UIColor.red let toView = context.view(forKey: UITransitionContextViewKey.to) let view = UIView(frame: CGRect.zero) ``` ### Generics 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 as `T`, `U`, or `V`. **Preferred**: ```swift struct Stack { ... } func write(to target: inout Target) func swap(_ a: inout T, _ b: inout T) ``` **Not Preferred**: ```swift struct Stack { ... } func write(to target: inout target) func swap(_ a: inout Thing, _ b: inout Thing) ``` ### Language Use US English spelling to match Apple's API. **Preferred**: ```swift let color = "red" ``` **Not Preferred**: ```swift let colour = "red" ``` ## Code Organization 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. ### Protocol Conformance 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**: ```swift class MyViewController: UIViewController { // class stuff here } // MARK: - UITableViewDataSource extension MyViewController: UITableViewDataSource { // table view data source methods } // MARK: - UIScrollViewDelegate extension MyViewController: UIScrollViewDelegate { // scroll view delegate methods } ``` **Not Preferred**: ```swift class MyViewController: 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 author. For UIKit view controllers, consider grouping lifecycle, custom accessors, and IBAction in separate class extensions. ### Unused Code Unused (dead) code, including Xcode template code and placeholder comments should be removed. An exception is when your tutorial or book instructs the user to use the commented code. Aspirational methods not directly associated with the tutorial whose implementation simply calls the superclass should also be removed. This includes any empty/unused UIApplicationDelegate methods. **Preferred**: ```swift override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return Database.contacts.count } ``` **Not Preferred**: ```swift override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return Database.contacts.count } ``` ### Minimal Imports Import only the modules a source file requires. For example, don't import `UIKit` when importing `Foundation` will suffice. Likewise, don't import `Foundation` if you must import `UIKit`. **Preferred**: ```swift import UIKit var view: UIView var deviceModels: [String] ``` **Preferred**: ```swift import Foundation var deviceModels: [String] ``` **Not Preferred**: ```swift import UIKit import Foundation var view: UIView var deviceModels: [String] ``` **Not Preferred**: ```swift import UIKit var deviceModels: [String] ``` ## Spacing * Indent using 2 spaces rather than tabs to conserve space and help prevent line wrapping. Be sure to set this preference in Xcode and in the Project settings as shown below: ![Xcode indent settings](screens/indentation.png) * 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. * Tip: You can re-indent by selecting some code (or **Command-A** to select all) and then **Control-I** (or **Editor ▸ 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**: ```swift if user.isHappy { // Do something } else { // Do something else } ``` **Not Preferred**: ```swift if user.isHappy { // Do something } else { // Do something else } ``` * There should be one blank line between methods and up to one blank line between type declarations 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 be no blank lines after an opening brace or before a closing brace. * Closing parentheses should not appear on a line by themselves. **Preferred**: ```swift let user = try await getUser( for: userID, on: connection) ``` **Not Preferred**: ```swift let user = try await getUser( for: userID, on: connection ) ``` * Colons always have no space on the left and one space on the right. Exceptions are the ternary operator `? :`, empty dictionary `[:]` and `#selector` syntax `addTarget(_:action:)`. **Preferred**: ```swift class TestDatabase: Database { var data: [String: CGFloat] = ["A": 1.2, "B": 3.2] } ``` **Not Preferred**: ```swift class TestDatabase : Database { var data :[String:CGFloat] = ["A" : 1.2, "B":3.2] } ``` * Long lines should be wrapped at around 70 characters. A hard limit is intentionally not specified. * Avoid trailing whitespaces at the ends of lines. * Add a single newline character at the end of each file. ## Comments When they are needed, use comments to explain **why** 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. ## Classes and Structures ### Which one to use? Remember, structs have [value semantics](https://developer.apple.com/library/mac/documentation/Swift/Conceptual/Swift_Programming_Language/ClassesAndStructures.html#//apple_ref/doc/uid/TP40014097-CH13-XID_144). 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 have [reference semantics](https://developer.apple.com/library/mac/documentation/Swift/Conceptual/Swift_Programming_Language/ClassesAndStructures.html#//apple_ref/doc/uid/TP40014097-CH13-XID_145). 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 to `AnyObject` or are historically modeled as classes already (`NSDate`, `NSSet`). Try to follow these guidelines as closely as possible. ### Example definition Here's an example of a well-styled class definition: ```swift class Circle: Shape { var x: Int, y: Int var radius: Double var diameter: Double { get { return radius * 2 } set { radius = newValue / 2 } } init(x: Int, y: Int, radius: Double) { self.x = x self.y = y self.radius = radius } convenience init(x: Int, y: Int, diameter: Double) { self.init(x: x, y: y, radius: diameter / 2) } override func area() -> Double { return Double.pi * radius * radius } } extension Circle: CustomStringConvertible { var description: String { return "center = \(centerString) area = \(area())" } private var centerString: String { return "(\(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`, and `Circle: 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 using `private` access control. ### Use of Self For conciseness, avoid using `self` since Swift does not require it to access an object's properties or invoke its methods. Use self only when required by the compiler (in `@escaping` closures, or in initializers to disambiguate properties from arguments). In other words, if it compiles without `self` then omit it. ### Computed Properties 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. **Preferred**: ```swift var diameter: Double { return radius * 2 } ``` **Not Preferred**: ```swift var diameter: Double { get { return radius * 2 } } ``` ### Final Marking classes or members as `final` in tutorials can distract from the main topic and is not required. Nevertheless, use of `final` can sometimes clarify your intent and is worth the cost. In the below example, `Box` has a particular purpose and customization in a derived class is not intended. Marking it `final` makes that clear. ```swift // Turn any generic type into a reference type using this Box class. final class Box { let value: T init(_ value: T) { self.value = value } } ``` ## Function Declarations Keep short function declarations on one line including the opening brace: ```swift func reticulateSplines(spline: [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: ```swift func reticulateSplines( spline: [Double], adjustmentFactor: Double, translateConstant: Int, comment: String ) -> Bool { // reticulate code goes here } ``` Don't use `(Void)` to represent the lack of an input; simply use `()`. Use `Void` instead of `()` for closure and function outputs. **Preferred**: ```swift func updateConstraints() -> Void { // magic happens here } typealias CompletionHandler = (result) -> Void ``` **Not Preferred**: ```swift func updateConstraints() -> () { // magic happens here } typealias CompletionHandler = (result) -> () ``` ## Function Calls Mirror the style of function declarations at call sites. Calls that fit on a single line should be written as such: ```swift let success = reticulateSplines(splines) ``` If the call site must be wrapped, put each parameter on a new line, indented one additional level: ```swift let success = reticulateSplines( spline: splines, adjustmentFactor: 1.3, translateConstant: 2, comment: "normalize the display") ``` ## Closure Expressions 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**: ```swift UIView.animate(withDuration: 1.0) { self.myView.alpha = 0 } UIView.animate(withDuration: 1.0, animations: { self.myView.alpha = 0 }, completion: { finished in self.myView.removeFromSuperview() }) ``` **Not Preferred**: ```swift UIView.animate(withDuration: 1.0, animations: { self.myView.alpha = 0 }) UIView.animate(withDuration: 1.0, animations: { self.myView.alpha = 0 }) { f in self.myView.removeFromSuperview() } ``` For single-expression closures where the context is clear, use implicit returns: ```swift attendeeList.sort { a, b in a > b } ``` 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 author. Examples: ```swift let value = numbers.map { $0 * 2 }.filter { $0 % 3 == 0 }.index(of: 90) let value = numbers .map {$0 * 2} .filter {$0 > 50} .map {$0 + 10} ``` ## Types 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**: ```swift let width = 120.0 // Double let widthString = "\(width)" // String ``` **Less Preferred**: ```swift let width = 120.0 // Double let widthString = (width as NSNumber).stringValue // String ``` **Not Preferred**: ```swift let width: NSNumber = 120.0 // NSNumber let widthString: NSString = width.stringValue // NSString ``` In drawing code, use `CGFloat` if it makes the code more succinct by avoiding too many conversions. ### Constants Constants are defined using the `let` keyword and variables with the `var` keyword. Always use `let` instead of `var` if the value of the variable will not change. **Tip:** A good technique is to define everything using `let` and only change it to `var` 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 use `static let`. Type properties declared in this way are generally preferred over global constants because they are easier to distinguish from instance properties. Example: **Preferred**: ```swift enum Math { static let e = 2.718281828459045235360287 static let root2 = 1.41421356237309504880168872 } let hypotenuse = side * Math.root2 ``` **Note:** The advantage of using a case-less enumeration is that it can't accidentally be instantiated and works as a pure namespace. **Not Preferred**: ```swift let e = 2.718281828459045235360287 // pollutes global namespace let root2 = 1.41421356237309504880168872 let hypotenuse = side * root2 // what is root2? ``` ### Static Methods and Variable Type Properties 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. ### Optionals Declare variables and function return types as optional with `?` where a `nil` value is acceptable. Use implicitly unwrapped types declared with `!` only for instance variables that you know will be initialized later before use, such as subviews that will be set up in `viewDidLoad()`. Prefer optional binding to implicitly unwrapped optionals in most 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: ```swift textContainer?.textLabel?.setNeedsDisplay() ``` Use optional binding when it's more convenient to unwrap once and perform multiple operations: ```swift if let textContainer = textContainer { // do many things with textContainer } ``` **Notes:** Swift 5.7 introduced new shorthand syntax for unwrapping optionals into shadowed variables: ```swift if let textContainer { // do many things with textContainer } ``` When naming optional variables and properties, avoid naming them like `optionalString` or `maybeView` since their optional-ness is already in the type declaration. For optional binding, shadow the original name whenever possible rather than using names like `unwrappedView` or `actualLabel`. **Preferred**: ```swift var subview: UIView? var volume: Double? // later on... if let subview = subview, let volume = volume { // do something with unwrapped subview and volume } // another example resource.request().onComplete { [weak self] response in guard let self = self else { return } let model = self.updateModel(response) self.updateUI(model) } ``` **Not Preferred**: ```swift var optionalSubview: UIView? var volume: Double? if let unwrappedSubview = optionalSubview { if let realVolume = volume { // do something with unwrappedSubview and realVolume } } // another example UIView.animate(withDuration: 2.0) { [weak self] in guard let strongSelf = self else { return } strongSelf.alpha = 1.0 } ``` ### Lazy Initialization Consider using lazy initialization for finer grained control over object lifetime. This is especially true for `UIViewController` that loads views lazily. You can either use a closure that is immediately called `{ }()` or call a private factory method. Example: ```swift lazy var locationManager = makeLocationManager() private func makeLocationManager() -> CLLocationManager { let manager = 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. ### Type Inference 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 as `CGFloat` or `Int16`. **Preferred**: ```swift let message = "Click the button" let currentBounds = computeViewBounds() var names = ["Mic", "Sam", "Christine"] let maximumWidth: CGFloat = 106.5 ``` **Not Preferred**: ```swift let message: String = "Click the button" let currentBounds: CGRect = computeViewBounds() var names = [String]() ``` #### Type Annotation for Empty Arrays and Dictionaries For empty arrays and dictionaries, use type annotation. (For an array or dictionary assigned to a large, multi-line literal, use type annotation.) **Preferred**: ```swift var names: [String] = [] var lookup: [String: Int] = [:] ``` **Not Preferred**: ```swift var names = [String]() var lookup = [String: Int]() ``` **NOTE**: Following this guideline means picking descriptive names is even more important than before. ### Syntactic Sugar Prefer the shortcut versions of type declarations over the full generics syntax. **Preferred**: ```swift var deviceModels: [String] var employees: [Int: String] var faxNumber: Int? ``` **Not Preferred**: ```swift var deviceModels: Array var employees: Dictionary var faxNumber: Optional ``` ## Functions vs Methods 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** ```swift let sorted = items.mergeSorted() // easily discoverable rocket.launch() // acts on the model ``` **Not Preferred** ```swift let sorted = mergeSort(items) // hard to discover launch(&rocket) ``` **Free Function Exceptions** ```swift let tuples = zip(a, b) // feels natural as a free function (symmetry) let value = max(x, y, z) // another free function that feels natural ``` ## Memory Management Code (even non-production, tutorial demo code) should not create reference cycles. Analyze your object graph and prevent strong cycles with `weak` and `unowned` references. Alternatively, use value types (`struct`, `enum`) to prevent cycles altogether. ### Extending object lifetime Extend object lifetime using the `[weak self]` and `guard let self = self else { return }` idiom. `[weak self]` is preferred to `[unowned self]` where it is not immediately obvious that `self` outlives the closure. Explicitly extending lifetime is preferred to optional chaining. **Preferred** ```swift resource.request().onComplete { [weak self] response in guard let self = self else { return } let model = self.updateModel(response) self.updateUI(model) } ``` **Not Preferred** ```swift // might crash if self is released before response returns resource.request().onComplete { [unowned self] response in let model = self.updateModel(response) self.updateUI(model) } ``` **Not Preferred** ```swift // deallocate could happen between updating the model and updating UI resource.request().onComplete { [weak self] response in let model = self?.updateModel(response) self?.updateUI(model) } ``` ## Access Control Full access control annotation in tutorials can distract from the main topic and is not required. Using `private` and `fileprivate` appropriately, however, adds clarity and promotes encapsulation. Prefer `private` to `fileprivate`; use `fileprivate` only when the compiler insists. Only explicitly use `open`, `public`, and `internal` 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 the `static` specifier or attributes such as `@IBAction`, `@IBOutlet` and `@discardableResult`. **Preferred**: ```swift private let message = "Great Scott!" class TimeMachine { private dynamic lazy var fluxCapacitor = FluxCapacitor() } ``` **Not Preferred**: ```swift fileprivate let message = "Great Scott!" class TimeMachine { lazy dynamic private var fluxCapacitor = FluxCapacitor() } ``` ## Control Flow Prefer the `for-in` style of `for` loop over the `while-condition-increment` style. **Preferred**: ```swift for _ in 0..<3 { print("Hello three times") } for (index, person) in attendeeList.enumerated() { print("\(person) is at position #\(index)") } for index in stride(from: 0, to: items.count, by: 2) { print(index) } for index in (0...3).reversed() { print(index) } ``` **Not Preferred**: ```swift var i = 0 while i < 3 { print("Hello three times") i += 1 } var i = 0 while i < attendeeList.count { let person = attendeeList[i] print("\(person) is at position #\(i)") i += 1 } ``` ### Ternary Operator 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 an `if` 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. **Preferred**: ```swift let value = 5 result = value != 0 ? x : y let isHorizontal = true result = isHorizontal ? x : y ``` **Not Preferred**: ```swift result = a > b ? x = c > d ? c : d : y ``` ## Golden Path When coding with conditionals, the left-hand margin of the code should be the "golden" or "happy" path. That is, don't nest `if` statements. Multiple return statements are OK. The `guard` statement is built for this. **Preferred**: ```swift func computeFFT(context: Context?, inputData: InputData?) throws -> Frequencies { guard let context = context else { throw FFTError.noContext } guard let inputData = inputData else { throw FFTError.noInputData } // use context and input to compute the frequencies return frequencies } ``` **Not Preferred**: ```swift func computeFFT(context: Context?, inputData: InputData?) throws -> Frequencies { if let context = context { if let inputData = inputData { // use context and input to compute the frequencies return frequencies } else { throw FFTError.noInputData } } else { throw FFTError.noContext } } ``` When multiple optionals are unwrapped either with `guard` or `if let`, minimize nesting by using the compound version when possible. In the compound version, place the `guard` on its own line, then indent each condition on its own line. The `else` clause is indented to match the `guard` itself, as shown below. Example: **Preferred**: ```swift guard let number1 = number1, let number2 = number2, let number3 = number3 else { fatalError("impossible") } // do something with numbers ``` **Not Preferred**: ```swift if let number1 = number1 { if let number2 = number2 { if let number3 = number3 { // do something with numbers } else { fatalError("impossible") } } else { fatalError("impossible") } } else { fatalError("impossible") } ``` ### Failing Guards Guard statements are required to exit in some way. Generally, this should be simple one line statement such as `return`, `throw`, `break`, `continue`, and `fatalError()`. Large code blocks should be avoided. If cleanup code is required for multiple exit points, consider using a `defer` block to avoid cleanup code duplication. ## Semicolons 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**: ```swift let swift = "not a scripting language" ``` **Not Preferred**: ```swift let swift = "not a scripting language"; ``` **NOTE**: Swift is very different from JavaScript, where omitting semicolons is [generally considered unsafe](https://stackoverflow.com/questions/444080/do-you-recommend-using-semicolons-after-every-statement-in-javascript) ## Parentheses Parentheses around conditionals are not required and should be omitted. **Preferred**: ```swift if name == "Hello" { print("World") } ``` **Not Preferred**: ```swift if (name == "Hello") { print("World") } ``` In larger expressions, optional parentheses can sometimes make code read more clearly. **Preferred**: ```swift let playerMark = (player == current ? "X" : "O") ``` ## Multi-line String Literals 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**: ```swift let message = """ 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**: ```swift let message = """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**: ```swift let message = "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." ``` ## No Emoji Do not use emoji in your projects. For those readers who actually type in their code, it's an unnecessary source of friction. While it may be cute, it doesn't add to the learning and it interrupts the coding flow for these readers. ## No #imageLiteral or #colorLiteral Likewise, do not use Xcode's ability to drag a color or an image into a source statement. These turn into #colorLiteral and #imageLiteral, respectively, and present unpleasant challenges for a reader trying to enter them based on tutorial text. Instead, use `UIColor(red:green:blue)` and `UIImage(imageLiteralResourceName:)`. ## Organization and Bundle Identifier Where an Xcode project is involved, the organization should be set to `Kodeco` and the Bundle Identifier set to `com.yourcompany.TutorialName` where `TutorialName` is the name of the tutorial project. ![Xcode Project settings](screens/project_settings.png) ## Copyright Statement The following copyright statement should be included at the top of every source file: ```swift /// Copyright (c) 2023 Kodeco Inc. /// /// Permission is hereby granted, free of charge, to any person obtaining a copy /// of this software and associated documentation files (the "Software"), to deal /// in the Software without restriction, including without limitation the rights /// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell /// copies of the Software, and to permit persons to whom the Software is /// furnished to do so, subject to the following conditions: /// /// The above copyright notice and this permission notice shall be included in /// all copies or substantial portions of the Software. /// /// Notwithstanding the foregoing, you may not use, copy, modify, merge, publish, /// distribute, sublicense, create a derivative work, and/or sell copies of the /// Software in any work that is designed, intended, or marketed for pedagogical or /// instructional purposes related to programming, coding, application development, /// or information technology. Permission for such use, copying, modification, /// merger, publication, distribution, sublicensing, creation of derivative works, /// or sale is expressly withheld. /// /// This project and source code may use libraries or frameworks that are /// released under various Open-Source licenses. Use of those libraries and /// frameworks are governed by their own individual licenses. /// /// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR /// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, /// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE /// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER /// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, /// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN /// THE SOFTWARE. ``` ## Smiley Face Smiley faces are a very prominent style feature of the [Kodeco](https://www.kodeco.com/) site! It is very important to have the correct smile signifying the immense amount of happiness and excitement for the coding topic. The closing square bracket `]` is used because it represents the largest smile able to be captured using ASCII art. A closing parenthesis `)` creates a half-hearted smile, and thus is not preferred. **Preferred**: ``` :] ``` **Not Preferred**: ``` :) ``` ## References * [The Swift API Design Guidelines](https://swift.org/documentation/api-design-guidelines/) * [The Swift Programming Language](https://developer.apple.com/library/prerelease/ios/documentation/swift/conceptual/swift_programming_language/index.html) * [Using Swift with Cocoa and Objective-C](https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/BuildingCocoaApps/index.html) * [Swift Standard Library Reference](https://developer.apple.com/library/prerelease/ios/documentation/General/Reference/SwiftStandardLibraryReference/index.html) ================================================ FILE: SWIFTLINT.markdown ================================================ # The Official Kodeco SwiftLint Policy The SwiftLint configuration in this repo is designed to ensure the work we create at Kodeco conforms with [The Official Kodeco Swift Style Guide](https://github.com/kodecocodes/swift-style-guide/blob/main/README.markdown). The focus of this style is to improve readability in our print and web publications. Therefore, this style may be different from others you've used, but the demands of print and online reading are different from other contexts. The policies described here have a goal of achieving consistency between all of our projects, which will also streamline the flow of content through our editing process. Some of the choices also aim to ensure we've removed as much of the burden from our readers as possible. These guides use SwiftLint as a standard. You can learn more about SwiftLint by visiting its [official documentation page](https://github.com/realm/SwiftLint). ## Table of Contents * [Installing SwiftLint](#installing-swiftlint) * [Using the Configuration File](#using-the-configuration-file) * [Xcode Settings](#xcode-settings) * [Running SwiftLint](#running-swiftlint) * [Handling Rule Exceptions](#handling-rule-exceptions) * [Approved Exceptions](#approved-exceptions) * [Implicitly Unwrapped Optionals](#implicitly-unwrapped-optionals) * [Force Cast](#force-cast) * [Force Unwrapping](#force-unwrapping) * [SwiftUI and Multiple Trailing Closures](#swiftui-and-multiple-trailing-closures) * [Open-Source Files](#open-source-files) * [Other Notes](#other-notes) ## Installing SwiftLint We recommend that Kodeco team members install SwiftLint using Homebrew: ```bash brew install swiftlint ``` If you are unable to use Homebrew, you may use one of the other methods described in the [SwiftLint documentation](https://github.com/realm/SwiftLint). **Do not** install SwiftLint as a CocoaPod in your project. ## Using the Configuration File **Do not** place the configuration file inside your project. We don't want to impose this style on readers without their express knowledge or understanding of what's going on. Download **com.raywenderlich.swiftlint.yml** from the [Swift Style Guide repo]([https://github.com/raywenderlich/swift-style-guide](https://github.com/kodecocodes/swift-style-guide/)) and place it your home directory: **~/com.raywenderlich.swiftlint.yml**. ## Xcode Settings You'll need to configure Xcode to remove trailing whitespace from all lines. This is not the default configuration. In Xcode's Preferences, select **Text Editing** ▸ **Editing** and check **Including whitespace-only lines**. ![](screens/trailing-whitespace.png) ## Running SwiftLint To simplify the process for everyone in the content pipeline, you'll need to add the necessary instructions to your sample project to run SwiftLint automatically on each build. To do so: 1. Select the project document in the Project navigator. 1. Select the **Build Phases** tab. 1. Click **+** and choose **New Run Script Phase**. ![](screens/add-run-script.png) 4. Drag the new phase before the **Compile Sources** phase. 4. Click the disclosure triangle on the **Run Script** phase and ensure **Shell** is set to **/bin/sh**. ![](screens/empty-run-script.png) 6. Add the following script: ``` PATH=/opt/homebrew/bin:$PATH if [ -f ~/com.raywenderlich.swiftlint.yml ]; then if which swiftlint >/dev/null; then swiftlint --no-cache --config ~/com.raywenderlich.swiftlint.yml fi fi ``` ## Handling Rule Exceptions Your sample project must compile without warnings — SwiftLint or otherwise. In general, you should change your code to eliminate all warnings where necessary. When it comes to SwiftLint, however, there will be times when this isn't possible. In these situations, you'll need to use in-line comments to temporarily disable rules. You can find appropriate syntax to do this in [the SwiftLint documentation](https://realm.github.io/SwiftLint/#disable-rules-in-code). You may only disable a rule if it is on the list of approved exceptions listed below. Prefer the form that disables a rule only for the next line: ``` // swiftlint:disable:next implicitly_unwrapped_optional var injectedValue: Data! ``` Or, similarly, for the previous line: ``` var injectedValue: Data! // swiftlint:disable:previous implicitly_unwrapped_optional ``` If there are several approved exceptions, group them together and disable the rule for that region. Be sure to enable the rule after that section. Do not leave a rule disabled throughout the source file. ``` // swiftlint:disable implicitly_unwrapped_optional var injectedValue1: Data! var injectedValue2: Data! // swiftlint:enable implicitly_unwrapped_optional ``` If you must disable rules in your project, leave those in-line comments in the project for the benefit of your teammates in the editing pipeline. Finally, if you're not sure which rule is triggering a warning, you can find the rule name in parentheses at the end of message: ![](screens/swiftlint-warning.png) ## Approved Exceptions There are certain common idioms that violate SwiftLint's strict checking. If you are unable to work around them — and you've already tried to find a better way to structure your code — you may disable rules as described in this section. If you find that you're struggling with rules other than those described below, please reach out to your Team Lead with your specific example. ### Implicitly Unwrapped Optionals It is sometimes common, in lieu of using dependency injection, to declare a child view controller's properties as Implicitly Unwrapped Optionals (IUO). If you're unable to structure your project to avoid this, you may disable the `implicitly_unwrapped_optional` rule for those dependency declarations. With the advent of `@IBSegueAction`, this should be rare. ### Force Cast You may use force casting — and disable the `force_cast` rule — in the `UITableViewDataSource` and `UICollectionViewDataSource` methods that dequeue cells. ### Force Unwrapping You may use forced unwrapping — rule name `force_unwrap` — when returning a color from an asset catalog: ``` static var rwGreen: UIColor { // swiftlint:disable:next force_unwrapping UIColor(named: "rw-green")! } ``` You may also use it in the same context as the force cast exception above, dequeuing cells in `UITableViewDataSource` and `UICollectionViewDataSource` methods. Although we prefer you to model appropriately defensive code for our readers, you may use force unwrapping to access resources that you _know_ are included in the app bundle. Finally, you may use force unwrapping when constructing a `URL` from a hard-coded, and guaranteed valid, URL string. ### SwiftUI and Multiple Trailing Closures Idiomatic SwiftUI uses trailing closures to provide the view content for certain user interface elements. `Button` is a prime example; it has an initializer form that uses a closure to provide its `label`. It's common to write something like the following: ``` Button(action: { self.isPresented.toggle() }) { Image(systemName: "plus") } ``` This violates the rule that you should not use trailing closure syntax when a method accepts multiple closure parameters, so SwiftLint will flag it with a warning. You can work around this by extracting the `Button`'s action into a separate method. While this is frequently a better solution when the action requires several statements, it's an onerous requirement when the action is a single statement, as in the example above. In these cases, you're permitted to disable this rule **for the declaration of a SwiftUI view** only. The rule name is `multiple_closures_with_trailing_closure`. ### Open-Source Files Occasionally, you'll find it necessary to include an unmodified open-source file in the sample project. It's a virtual certainty that these files won't comply with our style guide. Our practice has always been to leave these files in their original state. In this situation, you should disable SwiftLint for the entire file: ``` // swiftlint:disable all ``` ## Other Notes While SwiftLint goes a long way towards making your source code compliant with our style guide, it doesn't cover everything. For example, it won't catch or force you to correct the formatting for multi-condition `guard` statements. (See [Golden Path](https://github.com/raywenderlich/swift-style-guide#golden-path) for correct formatting.) This configuration has been tested against several dozen of our most recent tutorials. A couple of rules, such as the line length limit or the limit on the length of a function, may need tweaking to fit our style. If you find yourself butting heads with SwiftLint, please reach out to the iOS Team Lead with details. ================================================ FILE: com.raywenderlich.swiftlint.yml ================================================ excluded: - ${PWD}/Carthage - ${PWD}/Pods - ${PWD}/DerivedData disabled_rules: - discarded_notification_center_observer - notification_center_detachment - orphaned_doc_comment - todo analyzer_rules: - unused_import opt_in_rules: - array_init - attributes - closure_end_indentation - closure_spacing - collection_alignment - colon # promote to error - convenience_type - discouraged_object_literal - empty_collection_literal - empty_count - empty_string - enum_case_associated_values_count - fatal_error_message - first_where - force_unwrapping - implicitly_unwrapped_optional - indentation_width - last_where - legacy_random - literal_expression_end_indentation - multiline_arguments - multiline_function_chains - multiline_literal_brackets - multiline_parameters - multiline_parameters_brackets - operator_usage_whitespace - overridden_super_call - pattern_matching_keywords - prefer_self_type_over_type_of_self - redundant_nil_coalescing - redundant_type_annotation - strict_fileprivate - toggle_bool - trailing_closure - unneeded_parentheses_in_closure_argument - vertical_whitespace_closing_braces - vertical_whitespace_opening_braces - yoda_condition custom_rules: array_constructor: name: "Array/Dictionary initializer" regex: '[let,var] .+ = (\[.+\]\(\))' capture_group: 1 message: "Use explicit type annotation when initializing empty arrays and dictionaries" severity: warning attributes: always_on_same_line: - "@IBSegueAction" - "@IBAction" - "@NSManaged" - "@objc" force_cast: warning force_try: warning function_body_length: warning: 60 legacy_hashing: error identifier_name: excluded: - i - id - x - y - z indentation_width: indentation_width: 2 line_length: ignores_urls: true ignores_function_declarations: true ignores_comments: true multiline_arguments: first_argument_location: next_line only_enforce_after_first_closure_on_first_line: true private_over_fileprivate: validate_extensions: true trailing_whitespace: ignores_empty_lines: false ignores_comments: true vertical_whitespace: max_empty_lines: 2