{"id":3299,"url":"https://github.com/kodecocodes/swift-style-guide","last_synced_at":"2025-12-16T16:01:49.089Z","repository":{"id":37741332,"uuid":"20667410","full_name":"kodecocodes/swift-style-guide","owner":"kodecocodes","description":"The official Swift style guide for Kodeco.","archived":false,"fork":false,"pushed_at":"2025-04-01T18:21:22.000Z","size":2592,"stargazers_count":13165,"open_issues_count":16,"forks_count":2144,"subscribers_count":543,"default_branch":"main","last_synced_at":"2025-06-19T18:12:05.929Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/kodecocodes.png","metadata":{"files":{"readme":"README.markdown","changelog":null,"contributing":"CONTRIBUTING.markdown","funding":null,"license":"LICENSE.txt","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2014-06-10T00:52:42.000Z","updated_at":"2025-06-19T11:45:34.000Z","dependencies_parsed_at":"2024-04-09T13:13:32.668Z","dependency_job_id":"fc2dd5b0-31a5-4876-ab8e-b92835b634d5","html_url":"https://github.com/kodecocodes/swift-style-guide","commit_stats":null,"previous_names":["raywenderlich/swift-style-guide"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/kodecocodes/swift-style-guide","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kodecocodes%2Fswift-style-guide","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kodecocodes%2Fswift-style-guide/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kodecocodes%2Fswift-style-guide/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kodecocodes%2Fswift-style-guide/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/kodecocodes","download_url":"https://codeload.github.com/kodecocodes/swift-style-guide/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kodecocodes%2Fswift-style-guide/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":27767518,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-12-16T02:00:10.477Z","response_time":57,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-01-05T20:16:37.474Z","updated_at":"2025-12-16T16:01:49.054Z","avatar_url":"https://github.com/kodecocodes.png","language":null,"funding_links":[],"categories":["Style Guides","Guides","Others","Recently Updated","Programming Languages"],"sub_categories":["Other Xcode","Style Guides","[Jul 10, 2024](/content/2024/07/10/README.md)","Swift"],"readme":"# The Official Kodeco Swift Style Guide.\n### Updated for Swift 5\n\nThis 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.\n\nOur overarching goals are clarity, consistency and brevity, in that order.\n\n## Table of Contents\n\n* [Correctness](#correctness)\n* [Using SwiftLint](#using-swiftlint)\n* [Naming](#naming)\n  * [Prose](#prose)\n  * [Delegates](#delegates)\n  * [Use Type Inferred Context](#use-type-inferred-context)\n  * [Generics](#generics)\n  * [Class Prefixes](#class-prefixes)\n  * [Language](#language)\n* [Code Organization](#code-organization)\n  * [Protocol Conformance](#protocol-conformance)\n  * [Unused Code](#unused-code)\n  * [Minimal Imports](#minimal-imports)\n* [Spacing](#spacing)\n* [Comments](#comments)\n* [Classes and Structures](#classes-and-structures)\n  * [Use of Self](#use-of-self)\n  * [Protocol Conformance](#protocol-conformance)\n  * [Computed Properties](#computed-properties)\n  * [Final](#final)\n* [Function Declarations](#function-declarations)\n* [Function Calls](#function-calls)\n* [Closure Expressions](#closure-expressions)\n* [Types](#types)\n  * [Constants](#constants)\n  * [Static Methods and Variable Type Properties](#static-methods-and-variable-type-properties)\n  * [Optionals](#optionals)\n  * [Lazy Initialization](#lazy-initialization)\n  * [Type Inference](#type-inference)\n  * [Syntactic Sugar](#syntactic-sugar)\n* [Functions vs Methods](#functions-vs-methods)\n* [Memory Management](#memory-management)\n  * [Extending Object Lifetime](#extending-object-lifetime)\n* [Access Control](#access-control)\n* [Control Flow](#control-flow)\n  * [Ternary Operator](#ternary-operator)\n* [Golden Path](#golden-path)\n  * [Failing Guards](#failing-guards)\n* [Semicolons](#semicolons)\n* [Parentheses](#parentheses)\n* [Multi-line String Literals](#multi-line-string-literals)\n* [No Emoji](#no-emoji)\n* [No #imageLiteral or #colorLiteral](#no-imageliteral-or-colorliteral)\n* [Organization and Bundle Identifier](#organization-and-bundle-identifier)\n* [Copyright Statement](#copyright-statement)\n* [Smiley Face](#smiley-face)\n* [References](#references)\n\n\n## Correctness\n\nStrive to make your code compile without warnings. This rule informs many style decisions such as using `#selector` types instead of string literals.\n\n## Using SwiftLint\n\nWhen 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.\n\n## Naming\n\nDescriptive 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:\n\n- striving for clarity at the call site\n- prioritizing clarity over brevity\n- using `camelCase` (not `snake_case`)\n- using `UpperCamelCase` for types and protocols, `lowerCamelCase` for everything else\n- including all needed words while omitting needless words\n- using names based on roles, not types\n- sometimes compensating for weak type information\n- striving for fluent usage\n- beginning factory methods with `make`\n- naming methods for their side effects\n  - verb methods follow the -ed, -ing rule for the non-mutating version\n  - noun methods follow the formX rule for the mutating version\n  - boolean types should read like assertions\n  - protocols that describe _what something is_ should read as nouns\n  - protocols that describe _a capability_ should end in _-able_ or _-ible_\n- using terms that don't surprise experts or confuse beginners\n- generally avoiding abbreviations\n- using precedent for names\n- preferring methods and properties to free functions\n- casing acronyms and initialisms uniformly up or down\n- giving the same base name to methods that share the same meaning\n- avoiding overloads on return type\n- choosing good parameter names that serve as documentation\n- preferring to name the first parameter instead of including its name in the method name, except as mentioned under Delegates\n- labeling closure and tuple parameters\n- taking advantage of default parameters\n\n### Prose\n\nWhen referring to methods in prose, being unambiguous is critical. To refer to a method name, use the simplest form possible.\n\n1. Write the method name with no parameters.  **Example:** Next, you need to call `addTarget`.\n2. Write the method name with argument labels.  **Example:** Next, you need to call `addTarget(_:action:)`.\n3. Write the full method name with argument labels and types. **Example:** Next, you need to call `addTarget(_: Any?, action: Selector?)`.\n\nFor the above example using `UIGestureRecognizer`, 1 is unambiguous and preferred.\n\n**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.\n\n![Methods in Xcode jump bar](screens/xcode-jump-bar.png)\n\n\n### Class Prefixes\n\nSwift 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.\n\n```swift\nimport SomeModule\n\nlet myClass = MyModule.UsefulClass()\n```\n\n### Delegates\n\nWhen creating custom delegate methods, an unnamed first parameter should be the delegate source. (UIKit contains numerous examples of this.)\n\n**Preferred**:\n```swift\nfunc namePickerView(_ namePickerView: NamePickerView, didSelectName name: String)\nfunc namePickerViewShouldReload(_ namePickerView: NamePickerView) -\u003e Bool\n```\n\n**Not Preferred**:\n```swift\nfunc didSelectName(namePicker: NamePickerViewController, name: String)\nfunc namePickerShouldReload() -\u003e Bool\n```\n\n### Use Type Inferred Context\n\nUse compiler inferred context to write shorter, clear code.  (Also see [Type Inference](#type-inference).)\n\n**Preferred**:\n```swift\nlet selector = #selector(viewDidLoad)\nview.backgroundColor = .red\nlet toView = context.view(forKey: .to)\nlet view = UIView(frame: .zero)\n```\n\n**Not Preferred**:\n```swift\nlet selector = #selector(ViewController.viewDidLoad)\nview.backgroundColor = UIColor.red\nlet toView = context.view(forKey: UITransitionContextViewKey.to)\nlet view = UIView(frame: CGRect.zero)\n```\n\n### Generics\n\nGeneric 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`.\n\n**Preferred**:\n```swift\nstruct Stack\u003cElement\u003e { ... }\nfunc write\u003cTarget: OutputStream\u003e(to target: inout Target)\nfunc swap\u003cT\u003e(_ a: inout T, _ b: inout T)\n```\n\n**Not Preferred**:\n```swift\nstruct Stack\u003cT\u003e { ... }\nfunc write\u003ctarget: OutputStream\u003e(to target: inout target)\nfunc swap\u003cThing\u003e(_ a: inout Thing, _ b: inout Thing)\n```\n\n### Language\n\nUse US English spelling to match Apple's API.\n\n**Preferred**:\n```swift\nlet color = \"red\"\n```\n\n**Not Preferred**:\n```swift\nlet colour = \"red\"\n```\n\n## Code Organization\n\nUse 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.\n\n### Protocol Conformance\n\nIn 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.\n\n**Preferred**:\n```swift\nclass MyViewController: UIViewController {\n  // class stuff here\n}\n\n// MARK: - UITableViewDataSource\nextension MyViewController: UITableViewDataSource {\n  // table view data source methods\n}\n\n// MARK: - UIScrollViewDelegate\nextension MyViewController: UIScrollViewDelegate {\n  // scroll view delegate methods\n}\n```\n\n**Not Preferred**:\n```swift\nclass MyViewController: UIViewController, UITableViewDataSource, UIScrollViewDelegate {\n  // all methods\n}\n```\n\nSince 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.\n\nFor UIKit view controllers, consider grouping lifecycle, custom accessors, and IBAction in separate class extensions.\n\n### Unused Code\n\nUnused (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.\n\nAspirational methods not directly associated with the tutorial whose implementation simply calls the superclass should also be removed. This includes any empty/unused UIApplicationDelegate methods.\n\n**Preferred**:\n```swift\noverride func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -\u003e Int {\n  return Database.contacts.count\n}\n```\n\n**Not Preferred**:\n```swift\noverride func didReceiveMemoryWarning() {\n  super.didReceiveMemoryWarning()\n  // Dispose of any resources that can be recreated.\n}\n\noverride func numberOfSections(in tableView: UITableView) -\u003e Int {\n  // #warning Incomplete implementation, return the number of sections\n  return 1\n}\n\noverride func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -\u003e Int {\n  // #warning Incomplete implementation, return the number of rows\n  return Database.contacts.count\n}\n\n```\n### Minimal Imports\n\nImport 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`.\n\n**Preferred**:\n```swift\nimport UIKit\nvar view: UIView\nvar deviceModels: [String]\n```\n\n**Preferred**:\n```swift\nimport Foundation\nvar deviceModels: [String]\n```\n\n**Not Preferred**:\n```swift\nimport UIKit\nimport Foundation\nvar view: UIView\nvar deviceModels: [String]\n```\n\n**Not Preferred**:\n```swift\nimport UIKit\nvar deviceModels: [String]\n```\n\n## Spacing\n\n* 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:\n\n![Xcode indent settings](screens/indentation.png)\n\n* 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.\n* 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.\n\n**Preferred**:\n```swift\nif user.isHappy {\n  // Do something\n} else {\n  // Do something else\n}\n```\n\n**Not Preferred**:\n```swift\nif user.isHappy\n{\n  // Do something\n}\nelse {\n  // Do something else\n}\n```\n\n* 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.\n\n* There should be no blank lines after an opening brace or before a closing brace.\n\n* Closing parentheses should not appear on a line by themselves.\n\n**Preferred**:\n```swift\nlet user = try await getUser(\n  for: userID,\n  on: connection)\n```\n\n**Not Preferred**:\n```swift\nlet user = try await getUser(\n  for: userID,\n  on: connection\n)\n```\n\n* 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:)`.\n\n**Preferred**:\n```swift\nclass TestDatabase: Database {\n  var data: [String: CGFloat] = [\"A\": 1.2, \"B\": 3.2]\n}\n```\n\n**Not Preferred**:\n```swift\nclass TestDatabase : Database {\n  var data :[String:CGFloat] = [\"A\" : 1.2, \"B\":3.2]\n}\n```\n\n* Long lines should be wrapped at around 70 characters. A hard limit is intentionally not specified.\n\n* Avoid trailing whitespaces at the ends of lines.\n\n* Add a single newline character at the end of each file.\n\n## Comments\n\nWhen they are needed, use comments to explain **why** a particular piece of code does something. Comments must be kept up-to-date or deleted.\n\nAvoid 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._\n\nAvoid the use of C-style comments (`/* ... */`). Prefer the use of double- or triple-slash.\n\n## Classes and Structures\n\n### Which one to use?\n\nRemember, 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.\n\nClasses 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.\n\nSometimes, 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.\n\n### Example definition\n\nHere's an example of a well-styled class definition:\n\n```swift\nclass Circle: Shape {\n  var x: Int, y: Int\n  var radius: Double\n  var diameter: Double {\n    get {\n      return radius * 2\n    }\n    set {\n      radius = newValue / 2\n    }\n  }\n\n  init(x: Int, y: Int, radius: Double) {\n    self.x = x\n    self.y = y\n    self.radius = radius\n  }\n\n  convenience init(x: Int, y: Int, diameter: Double) {\n    self.init(x: x, y: y, radius: diameter / 2)\n  }\n\n  override func area() -\u003e Double {\n    return Double.pi * radius * radius\n  }\n}\n\nextension Circle: CustomStringConvertible {\n  var description: String {\n    return \"center = \\(centerString) area = \\(area())\"\n  }\n  private var centerString: String {\n    return \"(\\(x),\\(y))\"\n  }\n}\n```\n\nThe example above demonstrates the following style guidelines:\n\n + 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`.\n + Define multiple variables and structures on a single line if they share a common purpose / context.\n + Indent getter and setter definitions and property observers.\n + Don't add modifiers such as `internal` when they're already the default. Similarly, don't repeat the access modifier when overriding a method.\n + Organize extra functionality (e.g. printing) in extensions.\n + Hide non-shared, implementation details such as `centerString` inside the extension using `private` access control.\n\n### Use of Self\n\nFor conciseness, avoid using `self` since Swift does not require it to access an object's properties or invoke its methods.\n\nUse 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.\n\n\n### Computed Properties\n\nFor conciseness, if a computed property is read-only, omit the get clause. The get clause is required only when a set clause is provided.\n\n**Preferred**:\n```swift\nvar diameter: Double {\n  return radius * 2\n}\n```\n\n**Not Preferred**:\n```swift\nvar diameter: Double {\n  get {\n    return radius * 2\n  }\n}\n```\n\n### Final\n\nMarking 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.\n\n```swift\n// Turn any generic type into a reference type using this Box class.\nfinal class Box\u003cT\u003e {\n  let value: T\n  init(_ value: T) {\n    self.value = value\n  }\n}\n```\n\n## Function Declarations\n\nKeep short function declarations on one line including the opening brace:\n\n```swift\nfunc reticulateSplines(spline: [Double]) -\u003e Bool {\n  // reticulate code goes here\n}\n```\n\nFor functions with long signatures, put each parameter on a new line and add an extra indent on subsequent lines:\n\n```swift\nfunc reticulateSplines(\n  spline: [Double], \n  adjustmentFactor: Double,\n  translateConstant: Int, \n  comment: String\n) -\u003e Bool {\n  // reticulate code goes here\n}\n```\n\nDon't use `(Void)` to represent the lack of an input; simply use `()`. Use `Void` instead of `()` for closure and function outputs.\n\n**Preferred**:\n\n```swift\nfunc updateConstraints() -\u003e Void {\n  // magic happens here\n}\n\ntypealias CompletionHandler = (result) -\u003e Void\n```\n\n**Not Preferred**:\n\n```swift\nfunc updateConstraints() -\u003e () {\n  // magic happens here\n}\n\ntypealias CompletionHandler = (result) -\u003e ()\n```\n\n## Function Calls\n\nMirror the style of function declarations at call sites. Calls that fit on a single line should be written as such:\n\n```swift\nlet success = reticulateSplines(splines)\n```\n\nIf the call site must be wrapped, put each parameter on a new line, indented one additional level:\n\n```swift\nlet success = reticulateSplines(\n  spline: splines,\n  adjustmentFactor: 1.3,\n  translateConstant: 2,\n  comment: \"normalize the display\")\n```\n\n## Closure Expressions\n\nUse 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.\n\n**Preferred**:\n```swift\nUIView.animate(withDuration: 1.0) {\n  self.myView.alpha = 0\n}\n\nUIView.animate(withDuration: 1.0, animations: {\n  self.myView.alpha = 0\n}, completion: { finished in\n  self.myView.removeFromSuperview()\n})\n```\n\n**Not Preferred**:\n```swift\nUIView.animate(withDuration: 1.0, animations: {\n  self.myView.alpha = 0\n})\n\nUIView.animate(withDuration: 1.0, animations: {\n  self.myView.alpha = 0\n}) { f in\n  self.myView.removeFromSuperview()\n}\n```\n\nFor single-expression closures where the context is clear, use implicit returns:\n\n```swift\nattendeeList.sort { a, b in\n  a \u003e b\n}\n```\n\nChained 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:\n\n```swift\nlet value = numbers.map { $0 * 2 }.filter { $0 % 3 == 0 }.index(of: 90)\n\nlet value = numbers\n  .map {$0 * 2}\n  .filter {$0 \u003e 50}\n  .map {$0 + 10}\n```\n\n## Types\n\nAlways 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.\n\n**Preferred**:\n```swift\nlet width = 120.0                                    // Double\nlet widthString = \"\\(width)\"                         // String\n```\n\n**Less Preferred**:\n```swift\nlet width = 120.0                                    // Double\nlet widthString = (width as NSNumber).stringValue    // String\n```\n\n**Not Preferred**:\n```swift\nlet width: NSNumber = 120.0                          // NSNumber\nlet widthString: NSString = width.stringValue        // NSString\n```\n\nIn drawing code, use `CGFloat` if it makes the code more succinct by avoiding too many conversions.\n\n### Constants\n\nConstants 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.\n\n**Tip:** A good technique is to define everything using `let` and only change it to `var` if the compiler complains!\n\nYou 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:\n\n**Preferred**:\n```swift\nenum Math {\n  static let e = 2.718281828459045235360287\n  static let root2 = 1.41421356237309504880168872\n}\n\nlet hypotenuse = side * Math.root2\n\n```\n**Note:** The advantage of using a case-less enumeration is that it can't accidentally be instantiated and works as a pure namespace.\n\n**Not Preferred**:\n```swift\nlet e = 2.718281828459045235360287  // pollutes global namespace\nlet root2 = 1.41421356237309504880168872\n\nlet hypotenuse = side * root2 // what is root2?\n```\n\n### Static Methods and Variable Type Properties\n\nStatic 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.\n\n### Optionals\n\nDeclare variables and function return types as optional with `?` where a `nil` value is acceptable.\n\nUse 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.\n\nWhen accessing an optional value, use optional chaining if the value is only accessed once or if there are many optionals in the chain:\n\n```swift\ntextContainer?.textLabel?.setNeedsDisplay()\n```\n\nUse optional binding when it's more convenient to unwrap once and perform multiple operations:\n\n```swift\nif let textContainer = textContainer {\n  // do many things with textContainer\n}\n\n```\n**Notes:** Swift 5.7 introduced new shorthand syntax for unwrapping optionals into shadowed variables:\n\n```swift\nif let textContainer {\n  // do many things with textContainer\n}\n```\n\nWhen naming optional variables and properties, avoid naming them like `optionalString` or `maybeView` since their optional-ness is already in the type declaration.\n\nFor optional binding, shadow the original name whenever possible rather than using names like `unwrappedView` or `actualLabel`.\n\n**Preferred**:\n```swift\nvar subview: UIView?\nvar volume: Double?\n\n// later on...\nif let subview = subview, let volume = volume {\n  // do something with unwrapped subview and volume\n}\n\n// another example\nresource.request().onComplete { [weak self] response in\n  guard let self = self else { return }\n  let model = self.updateModel(response)\n  self.updateUI(model)\n}\n```\n\n**Not Preferred**:\n```swift\nvar optionalSubview: UIView?\nvar volume: Double?\n\nif let unwrappedSubview = optionalSubview {\n  if let realVolume = volume {\n    // do something with unwrappedSubview and realVolume\n  }\n}\n\n// another example\nUIView.animate(withDuration: 2.0) { [weak self] in\n  guard let strongSelf = self else { return }\n  strongSelf.alpha = 1.0\n}\n```\n\n### Lazy Initialization\n\nConsider 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:\n\n```swift\nlazy var locationManager = makeLocationManager()\n\nprivate func makeLocationManager() -\u003e CLLocationManager {\n  let manager = CLLocationManager()\n  manager.desiredAccuracy = kCLLocationAccuracyBest\n  manager.delegate = self\n  manager.requestAlwaysAuthorization()\n  return manager\n}\n```\n\n**Notes:**\n  - `[unowned self]` is not required here. A retain cycle is not created.\n  - Location manager has a side-effect for popping up UI to ask the user for permission so fine grain control makes sense here.\n\n\n### Type Inference\n\nPrefer 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`.\n\n**Preferred**:\n```swift\nlet message = \"Click the button\"\nlet currentBounds = computeViewBounds()\nvar names = [\"Mic\", \"Sam\", \"Christine\"]\nlet maximumWidth: CGFloat = 106.5\n```\n\n**Not Preferred**:\n```swift\nlet message: String = \"Click the button\"\nlet currentBounds: CGRect = computeViewBounds()\nvar names = [String]()\n```\n\n#### Type Annotation for Empty Arrays and Dictionaries\n\nFor empty arrays and dictionaries, use type annotation. (For an array or dictionary assigned to a large, multi-line literal, use type annotation.)\n\n**Preferred**:\n```swift\nvar names: [String] = []\nvar lookup: [String: Int] = [:]\n```\n\n**Not Preferred**:\n```swift\nvar names = [String]()\nvar lookup = [String: Int]()\n```\n\n**NOTE**: Following this guideline means picking descriptive names is even more important than before.\n\n\n### Syntactic Sugar\n\nPrefer the shortcut versions of type declarations over the full generics syntax.\n\n**Preferred**:\n```swift\nvar deviceModels: [String]\nvar employees: [Int: String]\nvar faxNumber: Int?\n```\n\n**Not Preferred**:\n```swift\nvar deviceModels: Array\u003cString\u003e\nvar employees: Dictionary\u003cInt, String\u003e\nvar faxNumber: Optional\u003cInt\u003e\n```\n\n## Functions vs Methods\n\nFree 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.\n\nFree functions are most appropriate when they aren't associated with any particular type or instance.\n\n**Preferred**\n```swift\nlet sorted = items.mergeSorted()  // easily discoverable\nrocket.launch()  // acts on the model\n```\n\n**Not Preferred**\n```swift\nlet sorted = mergeSort(items)  // hard to discover\nlaunch(\u0026rocket)\n```\n\n**Free Function Exceptions**\n```swift\nlet tuples = zip(a, b)  // feels natural as a free function (symmetry)\nlet value = max(x, y, z)  // another free function that feels natural\n```\n\n## Memory Management\n\nCode (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.\n\n### Extending object lifetime\n\nExtend 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.\n\n**Preferred**\n```swift\nresource.request().onComplete { [weak self] response in\n  guard let self = self else {\n    return\n  }\n  let model = self.updateModel(response)\n  self.updateUI(model)\n}\n```\n\n**Not Preferred**\n```swift\n// might crash if self is released before response returns\nresource.request().onComplete { [unowned self] response in\n  let model = self.updateModel(response)\n  self.updateUI(model)\n}\n```\n\n**Not Preferred**\n```swift\n// deallocate could happen between updating the model and updating UI\nresource.request().onComplete { [weak self] response in\n  let model = self?.updateModel(response)\n  self?.updateUI(model)\n}\n```\n\n## Access Control\n\nFull 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.\n\nOnly explicitly use `open`, `public`, and `internal` when you require a full access control specification.\n\nUse 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`.\n\n**Preferred**:\n```swift\nprivate let message = \"Great Scott!\"\n\nclass TimeMachine {  \n  private dynamic lazy var fluxCapacitor = FluxCapacitor()\n}\n```\n\n**Not Preferred**:\n```swift\nfileprivate let message = \"Great Scott!\"\n\nclass TimeMachine {  \n  lazy dynamic private var fluxCapacitor = FluxCapacitor()\n}\n```\n\n## Control Flow\n\nPrefer the `for-in` style of `for` loop over the `while-condition-increment` style.\n\n**Preferred**:\n```swift\nfor _ in 0..\u003c3 {\n  print(\"Hello three times\")\n}\n\nfor (index, person) in attendeeList.enumerated() {\n  print(\"\\(person) is at position #\\(index)\")\n}\n\nfor index in stride(from: 0, to: items.count, by: 2) {\n  print(index)\n}\n\nfor index in (0...3).reversed() {\n  print(index)\n}\n```\n\n**Not Preferred**:\n```swift\nvar i = 0\nwhile i \u003c 3 {\n  print(\"Hello three times\")\n  i += 1\n}\n\n\nvar i = 0\nwhile i \u003c attendeeList.count {\n  let person = attendeeList[i]\n  print(\"\\(person) is at position #\\(i)\")\n  i += 1\n}\n```\n\n### Ternary Operator\n\nThe 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.\n\n**Preferred**:\n\n```swift\nlet value = 5\nresult = value != 0 ? x : y\n\nlet isHorizontal = true\nresult = isHorizontal ? x : y\n```\n\n**Not Preferred**:\n\n```swift\nresult = a \u003e b ? x = c \u003e d ? c : d : y\n```\n\n## Golden Path\n\nWhen 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.\n\n**Preferred**:\n```swift\nfunc computeFFT(context: Context?, inputData: InputData?) throws -\u003e Frequencies {\n  guard let context = context else {\n    throw FFTError.noContext\n  }\n  guard let inputData = inputData else {\n    throw FFTError.noInputData\n  }\n\n  // use context and input to compute the frequencies\n  return frequencies\n}\n```\n\n**Not Preferred**:\n```swift\nfunc computeFFT(context: Context?, inputData: InputData?) throws -\u003e Frequencies {\n  if let context = context {\n    if let inputData = inputData {\n      // use context and input to compute the frequencies\n\n      return frequencies\n    } else {\n      throw FFTError.noInputData\n    }\n  } else {\n    throw FFTError.noContext\n  }\n}\n```\n\nWhen 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:\n\n**Preferred**:\n```swift\nguard \n  let number1 = number1,\n  let number2 = number2,\n  let number3 = number3 \nelse {\n  fatalError(\"impossible\")\n}\n// do something with numbers\n```\n\n**Not Preferred**:\n```swift\nif let number1 = number1 {\n  if let number2 = number2 {\n    if let number3 = number3 {\n      // do something with numbers\n    } else {\n      fatalError(\"impossible\")\n    }\n  } else {\n    fatalError(\"impossible\")\n  }\n} else {\n  fatalError(\"impossible\")\n}\n```\n\n### Failing Guards\n\nGuard 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.\n\n## Semicolons\n\nSwift 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.\n\nDo not write multiple statements on a single line separated with semicolons.\n\n**Preferred**:\n```swift\nlet swift = \"not a scripting language\"\n```\n\n**Not Preferred**:\n```swift\nlet swift = \"not a scripting language\";\n```\n\n**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)\n\n## Parentheses\n\nParentheses around conditionals are not required and should be omitted.\n\n**Preferred**:\n```swift\nif name == \"Hello\" {\n  print(\"World\")\n}\n```\n\n**Not Preferred**:\n```swift\nif (name == \"Hello\") {\n  print(\"World\")\n}\n```\n\nIn larger expressions, optional parentheses can sometimes make code read more clearly.\n\n**Preferred**:\n```swift\nlet playerMark = (player == current ? \"X\" : \"O\")\n```\n\n## Multi-line String Literals\n\nWhen 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.\n\n**Preferred**:\n\n```swift\nlet message = \"\"\"\n  You cannot charge the flux \\\n  capacitor with a 9V battery.\n  You must use a super-charger \\\n  which costs 10 credits. You currently \\\n  have \\(credits) credits available.\n  \"\"\"\n```\n\n**Not Preferred**:\n\n```swift\nlet message = \"\"\"You cannot charge the flux \\\n  capacitor with a 9V battery.\n  You must use a super-charger \\\n  which costs 10 credits. You currently \\\n  have \\(credits) credits available.\n  \"\"\"\n```\n\n**Not Preferred**:\n\n```swift\nlet message = \"You cannot charge the flux \" +\n  \"capacitor with a 9V battery.\\n\" +\n  \"You must use a super-charger \" +\n  \"which costs 10 credits. You currently \" +\n  \"have \\(credits) credits available.\"\n```\n\n## No Emoji\n\nDo 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.\n\n## No #imageLiteral or #colorLiteral\n\nLikewise, 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:)`.\n\n## Organization and Bundle Identifier\n\nWhere 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.\n\n![Xcode Project settings](screens/project_settings.png)\n\n## Copyright Statement\n\nThe following copyright statement should be included at the top of every source\nfile:\n\n```swift\n/// Copyright (c) 2023 Kodeco Inc.\n/// \n/// Permission is hereby granted, free of charge, to any person obtaining a copy\n/// of this software and associated documentation files (the \"Software\"), to deal\n/// in the Software without restriction, including without limitation the rights\n/// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n/// copies of the Software, and to permit persons to whom the Software is\n/// furnished to do so, subject to the following conditions:\n/// \n/// The above copyright notice and this permission notice shall be included in\n/// all copies or substantial portions of the Software.\n/// \n/// Notwithstanding the foregoing, you may not use, copy, modify, merge, publish,\n/// distribute, sublicense, create a derivative work, and/or sell copies of the\n/// Software in any work that is designed, intended, or marketed for pedagogical or\n/// instructional purposes related to programming, coding, application development,\n/// or information technology.  Permission for such use, copying, modification,\n/// merger, publication, distribution, sublicensing, creation of derivative works,\n/// or sale is expressly withheld.\n/// \n/// This project and source code may use libraries or frameworks that are\n/// released under various Open-Source licenses. Use of those libraries and\n/// frameworks are governed by their own individual licenses.\n///\n/// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n/// THE SOFTWARE.\n```\n\n## Smiley Face\n\nSmiley 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.\n\n**Preferred**:\n```\n:]\n```\n\n**Not Preferred**:\n```\n:)\n```\n\n## References\n\n* [The Swift API Design Guidelines](https://swift.org/documentation/api-design-guidelines/)\n* [The Swift Programming Language](https://developer.apple.com/library/prerelease/ios/documentation/swift/conceptual/swift_programming_language/index.html)\n* [Using Swift with Cocoa and Objective-C](https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/BuildingCocoaApps/index.html)\n* [Swift Standard Library Reference](https://developer.apple.com/library/prerelease/ios/documentation/General/Reference/SwiftStandardLibraryReference/index.html)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkodecocodes%2Fswift-style-guide","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fkodecocodes%2Fswift-style-guide","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkodecocodes%2Fswift-style-guide/lists"}