{"id":3304,"url":"https://github.com/prolificinteractive/swift-style-guide","last_synced_at":"2026-01-02T06:06:11.048Z","repository":{"id":50442287,"uuid":"44618802","full_name":"prolificinteractive/swift-style-guide","owner":"prolificinteractive","description":"A style guide for Swift.","archived":false,"fork":false,"pushed_at":"2017-06-02T17:51:07.000Z","size":187,"stargazers_count":176,"open_issues_count":4,"forks_count":20,"subscribers_count":47,"default_branch":"master","last_synced_at":"2025-01-20T20:53:30.295Z","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":"cc0-1.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/prolificinteractive.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2015-10-20T16:15:00.000Z","updated_at":"2024-10-06T14:56:51.000Z","dependencies_parsed_at":"2022-09-13T11:12:02.276Z","dependency_job_id":null,"html_url":"https://github.com/prolificinteractive/swift-style-guide","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/prolificinteractive%2Fswift-style-guide","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/prolificinteractive%2Fswift-style-guide/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/prolificinteractive%2Fswift-style-guide/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/prolificinteractive%2Fswift-style-guide/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/prolificinteractive","download_url":"https://codeload.github.com/prolificinteractive/swift-style-guide/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":243508983,"owners_count":20302106,"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","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.618Z","updated_at":"2026-01-02T06:06:10.996Z","avatar_url":"https://github.com/prolificinteractive.png","language":null,"funding_links":[],"categories":["Unofficial","Style Guides","WebSocket"],"sub_categories":["Other Xcode","Keychain","Other free courses"],"readme":"![Swift Style Guide](Swift_style_guide.jpg)\n\n# Table Of Contents\n\n* [Overview](#overview)\n* [Linter](#linter)\n* [Standards](#standards)\n\t* [Naming Conventions](#naming-conventions)\n\t* [File Structure](#file-structure)\n\t* [Types](#types-1)\n\t* [Statement Termination](#statement-termination)\n\t* [Variable Declaration](#variable-declaration)\n\t* [Self](#self)\n\t* [Structs \u0026 Classes](#structs--classes)\n\t* [Bracket Syntax](#bracket-syntax)\n\t* [Force Unwrap](#force-unwrap)\n\t* [Error Handling](#error-handling)\n\t* [Access Modifiers](#access-modifiers)\n\t* [Imports](#imports)\n\t* [Nil Checking](#nil-checking)\n\t* [Implicit Getters](#implicit-getters)\n\t* [Enums](#enums)\n\t* [Use of `final`](#use-of-final)\n\t* [Operators](#operators)\n\t* [Documentation](#documentation)\n* [Best Practices](BestPractices.md)\n\n\n# Overview\n\nThis is Prolific's style guide for writing code in Swift. The purpose of this guide is to develop\na universal standard for Swift code that makes our codebases consistent and easy to read. This guide aims for\nconsistent and clean code written in Swift in line with Apple and the general community.\n\nThe standards have been influenced by:\n\n* Apple's language design decisions -- specifically, its desire for Swift code to be written concisely and expressively\n* Xcode's defaults for code formatting\n* The general community\n\n### Contributing\n\nIf you wish to contribute, feel free to submit a pull request or file an issue on this repo. In the pull request, be sure to discuss what problem you are intending\nto solve and the rationale to do so. When submitting a pull request, consider:\n\n* Is my suggestion general enough to be considered a code standard for all code bases?\n* Does my suggestion fall in line with Apple's desire for the language?\n* Does your suggestion invalidate a language feature?\n\nMake sure to consider the resources in the open-source Swift repo; specifically, read through the various\n[proposals](https://github.com/apple/swift-evolution/tree/master/proposals) for new language features as well as the\n[most-commonly rejected proposals](https://github.com/apple/swift-evolution/blob/master/commonly_proposed.md) in order to\nguide your design principals.\n\n# Linter\n\nIn order to automate many of the rules here, we recommend using [our fork of Swiftlint](https://github.com/prolificinteractive/SwiftLint) in your Swift codebase.\nWhile the main fork of Swiftlint is based around the GitHub style guide for Swift, our fork has additional rules and corrections for rules specific to our\nstyle guide that you will not find in the GitHub one.\n\n\n# Standards\n\n## Naming Conventions\n\nThe Apple Swift [API design guidelines](https://swift.org/documentation/api-design-guidelines/) promote clarity over brevity. Code should be concise, readable and clear at the point of use. However, having compact code that sacrifices clarity is a non-goal.\n\n### Types\n\nWrite all type names with UpperCamelCase, function and variable names with lowerCamelCase.\n\n```swift\nclass MyClass { }\nprotocol MyProtocol { }\nfunc myFunction() { }\nvar myVariable: String\n```\n\nAvoid acronyms and abbreviations for clarity and readability. If you have to use an acronym, use upper case.\n\n```swift\nproductURL = NSURL()\nuserID = \"12345\"\n```\n\n### Protocols\n\nProtocol names describing something should be a noun: `Collection`, `Element`. Protocol names describing an ability should end with “ing” or “able”: `Evaluatable`, `Printable`, `Formatting`.\n\n### Enums\n\nEnum cases start with lowerCamelCase.\n\n```\nenum Color {\n    case red\n    case blue\n    case green\n    case lightBlue\n}\n```\n\n### Functions\n\nName your function with words that describe its behavior. Here is an example with a function that removes an element at an index x.\n\n**Preferred:**\n```swift\nfunc remove(at index: Index) -\u003e Element\n```\n\n**Not Preferred:**\n```swift\nfunc remove(index: Index) -\u003e Element\n```\n\n*Rationale*: It is better to specify that we are removing the element at the given index, and we are not trying to remove the given parameter itself, to make the behavior of the function very clear.\n\nAvoid unnecessary words in the function name.\n\n**Preferred:**\n```swift\nfunc remove(_ element: Element) -\u003e Element?\n```\n\n**Not Preferred:**\n```swift\nfunc removeElement(_ element: Element) -\u003e Element?\n```\n\n*Rationale*: It makes the code clearer and more concise. Adding extra unnecessary words will make the code harder to read and understand.\n\nName your functions based on their side effects and behaviors.\n\n* With side effects: use **imperative verb** phrases:\n\t* `print(x)`, `x.sort()`, `x.append(y)`\n* Without side effects: use **noun** phrases:\n\t* `x.formattedName()`, `x.successor()`\n\nWhen the function can be described by a verb, use an imperative verb for the mutating function and apply “ed” or “ing” to the nonmutating function:\n* Mutating function:\n\t* `x.sort()`\n\t* `x.append(y)`\n* Nonmutating function:\n\t* `z = x.sorted()`\n\t* `z = x.appending(y)`\n\nName functions to be read as a sentence according to their side effects.\n\n**Preferred:**\n```swift\nx.insert(y, at: z)          // x, insert y at z\nx.subViews(havingColor: y)  // x's subviews having color y\nx.capitalizingNouns()       // x, capitalizing nouns\n```\n\n**Not Preferred:**\n```swift\nx.insert(y, position: z)\nx.subViews(color: y)\nx.nounCapitalize()\n```\n\n### Empty Return Types\n\nWhen specifying return type for functions, methods or closures that return no value, favor the type alias `Void` over empty tuple `()`.\n\n**Preferred:**\n```swift\nfunc performTask(_ completion: @escaping (Bool) -\u003e Void)\n```\n\n**Not Preferred:**\n```swift\nfunc performTask(_ completion: @escaping (Bool) -\u003e ())\n```\n\n## File structure\n\nYou should not define multiple public/internal types (ie class, struct, enum) in the same file; each type should have its own file.\n\nThe following list should be the standard organization of all your Swift files, in this specific order:\n\nBefore the type declaration:\n\n* Private Class/Struct/Enum\n\nInside the type declaration:\n\n* Override Properties\n* Properties\n* Static/Class Variables\n* Static/Class Functions\n* Init/Deinit\n* Override Functions\n* Instance Functions\n\nAfter the type declaration:\n\n* Extensions\n\nEach section above should be organized by accessibility:\n\n* Open\n* Public\n* Internal\n* Fileprivate\n* Private\n\nWhen implementing a protocol you should create an extension of your class that lives in the same file to separate the core logic of your class and your protocol implementation.\n\n### Enum \u0026 Protocol\n\nAll enums should live in their own file, except in cases where the enum is declared as private. In cases where the enum is declared private, declare the enum at the top of the file, above the type declaration.\n\n*Rationale*: With enum and protocol types Swift allows defining functions and extensions. Because of that these types can become complex which is why they should be defined in their own file.\n\n### Usage of MARK / TODO / FIXME\n\nTo help organize your files you may want to use pragma marks to clearly separate your functions, properties and extensions. For extensions, use one MARK per extension. For example, `// MARK: UITableViewDelegate Functions` instead of `// MARK: Extensions`.\n\nXcode is also able to display `TODO` and `FIXME` tags directly in the source navigator, you should consider using them to find your notes inside your files.\n\n`// TODO: implement this feature`\n\n`// FIXME: fix it it's not working`\n\nOther conventional comment tags, such as `NOTE` are not recognized by Xcode.\n\n## Types\n\nPrefer Swift native types over Objective-C types when possible. Because Swift types bridge to Objective-C, you should avoid types like NSString and NSNumber in favor of Int or String.\n\n*Rationale*: Avoid subclassing NSObject or using the @objc flag unless it is required to implement an NSObjectProtocol type. Subclassing NSObject or using the @objc flag automatically creates an Objective-C object that uses dynamic dispatch over the preferred static of Swift which can impact the performance of the app.\n\n**Preferred:**\n\n```swift\nclass MyClass {\n...\n}\n```\n\n**Not preferred:**\n\n```swift\n@objc class MyClass {\n...\n}\n```\n\nIf you need functionality from an Objective-C type that is not available in its corresponding Swift type (for instance, needing an NSString function that is not available on String), cast your Swift raw type to the corresponding Objective-C type instead of declaring the type as the Objective-C type.\n\n**Preferred:**\n\n```swift\nlet scale = 5.0\nlet scaleString = (5.0 as NSNumber).stringValue\nlet scaleInt = Int(scale)\n```\n\n**Not preferred:**\n\n```swift\nlet scale: NSNumber = 5.0\nlet scaleString = scale.stringValue\nlet scaleInt = scale.integerValue\n```\n\nAlways use Swift equivalent of an Objective-C function whenever possible. For example when manipulating a CGRect variable:\n\n**Preferred:**\n```swift\nlet rect = CGRect()\nlet width = rect.width\nlet height = rect.height\n```\n\n**Not preferred:**\n```swift\nlet rect = CGRect()\nlet width = CGRectGetWidth(rect)\nlet height = CGRectGetHeight(rect)\n```\n\n*Rationale*: Objective-C functions are making the code less readable, also using Swift equivalents will always help transitioning from a Swift version to another.\n\n### Type Declarations\n\nWhen declaring types, the colon should be placed immediately after the identifier followed by one space and the type name.\n\n```swift\n\nvar intValue: Int\n\n// Do NOT do this\nvar intValue : Int\n\n```\n\nIn all use-cases, the colon should be associated with the left-most item with no spaces preceding and one space afterwards:\n\n```swift\nlet myDictionary: [String: AnyObject] = [\"String\": 0]\n```\n\n### typealias\n\nTypealias declarations should precede any other type declaration.\n\n```swift\n// typealias ClosureType = (ParameterTypes) -\u003e (ReturnType)\ntypealias AgeAndNameProcessor = (Int, String) -\u003e Void\n\nvar intValue: Int\n\nclass Object {\n\n\tprivate var someString = \"\"\n\n\tfunc returnOne() -\u003e Int {\n\t\treturn 1\n\t}\n\n}\n```\n\nIf declaring a typealias for protocol conformance, it should be declared at the top of the type declaration, before anything else.\n\n\n```swift\nprotocol Configurable {\n\n    associatedtype InputData\n\n    func configure(data: InputData) -\u003e Void\n\n}\n\nclass ExampleWillNeed {\n\n    var x: String = \"\"\n    var y: String = \"\"\n\n}\n\nclass Example: Configurable {\n\n    typealias InputData = ExampleWillNeed\n\n    var a: String = \"\"\n    var b: String = \"\"\n\n    func configure(data: InputData)  {\n        a = data.x\n        b = data.y\n    }\n\n}\n```\n\n### Type Inference\n\nPrefer letting the compiler infer the type instead of explicitly stating it, wherever possible:\n\n```swift\nvar max = 0 \t\t// Int\nvar name = \"John\" \t// String\nvar rect = CGRect()\t// CGRect\n\n// Do not do:\n\nvar max: Int = 0\nvar name: String = \"John\"\nvar rect: CGRect = CGRect()\n\n// Ok since the inferred type is not what we wanted:\n\nvar max: Hashable = 0 // Compiler would infer Int, but we only want it to be hashable\nvar name: String? = \"John\" // Compiler would infer this not to be optional, but we may need to nil it out later.\n```\n\n*Rationale* The compiler is pretty smart, and we should utilize it where necessary. It is generally obvious what the\ntype is going to be in the instances above, so unless we need to be more explicit (as in the last examples above), it is better to omit unneeded words.\n\n## Statement Termination\n\nUnlike Objective-C, omit the use of `;` to terminate statements. Instead, simply use new lines to indicate the end of a statement.\n\n```swift\nlet myVar = 0\ndoSomething(myVar)\n\nreturn\n```\n\nAvoid multiple statements on a single line.\n\n```swift\nguard let obj = myObj else { print(\"Something went wrong\"); return; } // Wrong! Instead, place each item on its own line.\n```\n\n## Variable Declaration\n\nFor declaring variables, favor `let` instead of `var` unless you need a mutable object or container.\n\n```swift\nfunc formatDate(date: NSDate) -\u003e String {\n    let dateFormatter = NSDateFormatter() // In this case, use `let` since the variable `dateFormatter` never changes once set\n    dateFormatter.dateStyle = .ShortStyle\n    return dateFormatter.stringFromDate(date)\n}\n\nfunc arrays() {\n    let array = [\"Hello\", \"Ciao\", \"Aloha\"] // use let here since this is an immutable container\n\n    var mutableArray = [String]() // Use var here since this container is mutable\n    mutableArray.append(\"Farewell\")\n    mutableArray.append(\"Arrivederci\")\n}\n\n```\n\n## Self\n\nNever use the `self` modifier except in cases where it is necessary for the compiler or to alleviate conflicts\nwith other variable declarations.\n\n```swift\n\nclass Object {\n\tprivate var name = \"\"\n\n\tfunc useName() {\n\t\t// Let self be implied when it can be understood.\n\t\totherObject.doSomethingWithName(name)\n\t\tsetName(\"Will Smith\")\n\t}\n\n\tfunc setName(name: String) {\n\t\t// Use self here to prevent conflicts with the `name` parameter being passed.\n\t\tself.name = name\n\t}\n\n\tfunc setNameAsync(newName: String) {\n\t\t// Use implicit self outside closures...\n\t\totherObject.doSomethingWithName(name, then: {\n\t\t\t// .. but within, you must use self to ease the compiler.\n\t\t\tself.setName(\"Jason\")\n\t\t})\n\t}\n}\n\n```\n\n*Rationale*: The idea behind this is that implicit use of self makes the conditions where you _must_ use self\n(for instance, within closures) much more apparent and will make you think more on the reasons why you are using it.\nIn closures, think about: should `self` be `weak` instead of `strong`? Apple has even rejected a request to enforce use of `self` for this reason, [among others](http://ericasadun.com/2016/01/06/the-swift-evolution-proposal-se-0009-rejection/).\n\n\n## Bracket Syntax\n\nFor brackets, prefer the Xcode-default syntax of having the opening brace be on the same line as the statement opening it:\n\n```swift\nfinal class MyObject {\n}\n\nenum MyEnum {\n}\n\nfunc doSomething() {\n}\n\nif true == false {\n}\n\nlet doSomething: () -\u003e Void = {\n}\n\n```\n\nFor type declarations, include a single space between the type declaration and the first item implemented within\nit:\n\n```swift\nfinal class MyObject {\n\n\tlet value = 0\n```\n\nIn addition, include a space before the type declaration's closing bracket:\n\n```swift\nfinal class MyObject {\n\n\tlet value = 0\n\n\tfunc doSomething() {\n\t\tvalue += 1\n\t}\n\n}\n```\n\nThis also applies to extension declarations:\n\n```swift\nextension MyObject {\n\n\tfunc doAnotherThing() {\n\t\t...\n\t}\n\n}\n```\n\nDo not include this extra space in function declarations:\n\n```swift\nfunc doSomething() {\n\tlet value = 0\n}\n```\n\n*Rationale*: Simply put, this is the Xcode default and standard, and it's not worth fighting. This keeps things consistent\nacross the board and makes our lives as developers considerably easier.\n\n## Force Unwrap\n\nUnless there is a situation that absolutely calls for it, usage of the force-unwrap operator `(!)` should\nbe minimized, if not eliminated all together. With the many and varied ways of unwrapping optionals, it is\nsafer and simpler to declare variables as optional and unwrap them when needing their values than it is\nto force-unwrap them and potentially introduce runtime errors into the code base.\n\n```swift\n\nif let text = self.textLabel?.text {\n    doSomethingWithText(text)\n}\n\n```\n\nIf you are interoping from Objective-C and the declaration automatically translates into force-unwrapped\nparameters, replace them with `?` parameters instead.\n\nThe one exception to this rule are IBOutlets. @IBOutlets may be declared using `!` so long as they are expected\nto exist for the lifetime of the view controller object:\n\n```swift\n@IBOutlet private weak var textLabel: UILabel!\n\n```\n\n## Error Handling\n\nThe emergence of `try / catch` in Swift 2 has added powerful ways to define and return errors when something fails. The emergence of `ErrorType`\nas well for defining errors makes error definitions much more convenient over the cumbersome `NSError`. Because of this, for functions that can have multiple\npoints of failure, you should always define it as `throws` and return a well-defined `ErrorType`.\n\nConsider the following contrived example:\n\n```swift\n\nfunc multiplyEvensLessThan10(evenNumber: Int) -\u003e Int? {\n\tguard evenNumber % 2 == 0 \u0026\u0026 evenNumber \u003c 10 else {\n\t\treturn nil\n\t}\n\n\treturn evenNumber * 2\n}\n\n```\n\nThe function above fails because it only expects evens less than 10 and returns an optional if that is violated. While this works and is simple, it\nis more Objective-C than Swift in its composition. The caller may not know which parameter they violated. For Swift, instead consider refactoring it as follows:\n\n```swift\n\nenum NumberError: ErrorType {\n\tcase notEven\n\tcase tooLarge\n}\n\nfunc multiplyEvens(evenNumber: Int) throws -\u003e Int {\n\tguard evenNumber % 2 == 0 else {\n\t\tthrow NumberError.NotEven\n\t}\n\n\tguard evenNumber \u003c 10 else {\n\t\tthrow NumberError.TooLarge\n\t}\n\n\treturn evenNumber * 2\n}\n\n```\n\nThe above, while slightly more cumbersome, this has well-defined benefits:\n\n* The caller is able to explicitly determine why their call to the function failed and thus can take active steps to recover:\n\n\t```swift\n\tlet result: Int\n\tdo {\n\t    result = try multiplyEvens(3)\n\t} catch NumberError.NotEven {\n\t    return 0\n\t} catch NumberError.TooLarge {\n\t    print(\"The Number entered was too large! Try again.\")\n\t    return -1\n\t} catch {\n\t    fatalError(\"Unhandled error occurred.\")\n\t}\n\n\treturn result\n\t```\n\n* Try/catch semantics allow the caller to still retain the old optional functionality if the error is not relevant and they only care about the outcome:\n\n\t```swift\n\tlet result: Int? = try? multiplyEvens(1)\n\t```\n\n* Or, if the caller knows that it will not violate any of the parameters for a valid input:\n\n\t```swift\n\tlet result: Int = try! multiplyEvens(2)\n\t```\n\nSo, even though we've now modified our API to use swift exceptions, we can still retain the old Objective-C functionality giving the caller the choice\nof how they wish to handle the result of this failable operation.\n\n### NSError\n\nIn general, you should avoid `NSError` in Swift in favor of defining your own `ErrorType`. However, in the event you do need to use `NSError` (for interop with Objective-C, for instance):\n\n* Define a proper domain for your `NSError`. This should be specific to your module and ideally would be reflective of your bundle identifier (e.g. `com.prolificinteractive.MyApp`).\n* Define a list of the various error codes and what they translate to. These should be some sort of easily readable constant or enum value so that way the caller is able to determine what exactly failed.\n* In the userInfo, include _at least_ a localized description (`NSLocalizedDescriptionKey`) that accurately and concisely describes the nature of the error.\n\n## Access Modifiers\n\nSpecify access modifiers only when they are needed and required by the compiler. For `internal` types and functions, do not explicitly specify the access modifier since all entities in Swift are `internal` by default.\n\n```swift\nfinal class Object {\n\n    var myInt: Int\n\n    private func doWork() {\n        ...\n    }\n\n}\n\n```\n\nFurther, the access modifier should always be presented first in the list before any other modifiers:\n\n```swift\n// Good!\nprivate unowned var obj: Object\n\nfunc doSomething() {\n}\n\n// Wrong!\nweak public var obj: Object?\n```\n\n## Imports\n\nImport statements should be at the very top of the code file, and they should be listed in alphabetical order.\n\n```swift\nimport AFNetworking\nimport Foundation\nimport ReactiveCocoa\nimport RealmSwift\nimport UIKit\n```\n\nThe exception is for imports that are for testing only; they should be placed at the bottom of the list, in alphabetical order:\n\n```swift\nimport AFNetworking\nimport UIKit\n@testable import MyLibrary\n```\n\n## Structs \u0026 Classes\n\nIn Swift, structs maintain value semantics which means their values are copied when assigned. Classes, on the other hand, act like pointers from C\nand Objective-C; they are called reference types and the internal data is shared amongst instances of assigning.\n\nWhen composing your types, consider carefully what they're going to be used for before choosing what they should end up being. In general,\nconsider structs for types that are:\n\n* Immutable\n* Stateless\n* Have a definition for equality\n\nSwift structs also have other, tangible benefits as well:\n\n* Faster\n* Safer due to copying rather than referencing\n* Thread safe -- copies allow mutations to happen independently of other instances.\n\nIn general, you should favor structs and protocols over classes; even in cases where polymorphism would dictate the usage of a class, consider if you can\nachieve a similar result via protocols and extensions. This allows you to achieve polymorphism via *composition* rather than *inheritance*.\n\n## Nil Checking\n\nFavor `if-let` checking over direct nil checking in all cases except when the result of this check is required:\n\n```swift\nguard let item = myItem else {\n\treturn\n}\n\ndoSomethingWith(item)\n```\n\n```swift\nif let _ = error { // Prefer this over `if error != nil`\n\tfatalError()\n}\n```\n\n```swift\nfunc isError(error: Error?) -\u003e Bool {\n\treturn (error != nil) // In this case, we need the result of the bool, and this is much cleaner than the other options.\n}\n```\n\nFor style suggestions regarding nil checking visit our [best practices](https://github.com/prolificinteractive/swift-style-guide/blob/master/BestPractices.md) section.\n\n## Implicit Getters\n\nWhen overriding only the getter of a property, omit the use of `get`:\n\n```swift\nvar myInt: Int {\n\treturn 0\n}\n\n// Do not do this:\nvar myInt: Int {\n\tget {\n\t\treturn 0\n\t}\n}\n\n```\n\nFor all other cases, specify the modifier as needed (`set`, `didSet`, etc.). This is compiler enforced.\n\n*Rationale* The getter is implied enough to make sense without having to make it explicitly. It also cuts down on\nunnecessary verbiage and spacing to make code clearer.\n\n## Enums\n\nFor enum declarations, declare each enum case on a new line with its own `case` statement instead of a comma-separated list.\n\n```swift\nenum State {\n\tcase open\n\tcase closed\n\tcase pending\n\tcase faulted\n}\n```\n\nPrefer singular case for enum names instead of plural: `State` vs. `States`:\n\n```swift\nvar currentState = State.open\nvar previousState = States.closed // Reads less clearly than the previous option.\n```\n\nFor enums with raw values, declare the raw value on the same line as its declaration:\n\n```swift\nenum HTTPMethod: String {\n\tcase get = \"GET\"\n\tcase post = \"POST\"\n}\n```\n\nFor any other functions or properties associated with the enum, place them after the last case item in the enum list:\n\n```swift\nenum State {\n\tcase open\n\tcase closed\n\tcase pending\n\tcase faulted\n\n\tfunc nextState() -\u003e State {\n\t\t...\n\t}\n}\n```\n\nIn cases where the enum's type name can be omitted, do so:\n\n```swift\nlet state = State.open\n\nif state == .closed { ... // Prefer .closed instead of State.closed\n```\n\n\n## Use of `final`\n\nClasses should always be marked as `final` unless they are being used as a base class for another type. In instances where a class can be subclassed,\nany function or variable that should not be overridden by a subclass should be diligently marked as `final`.\n\n```swift\n// Not built for inheritance.\nfinal class Object {\n\n}\n\n// Purposefully utilizable as a base class\nclass BaseClass {\n\n\tfunc doSomething () {\n\t}\n\n\t// Properly marked as final so subclasses cannot override\n\tfinal func update() {\n\t}\n\n}\n\nfinal class SubClass: BaseClass {\n\n\toverride func doSomething() {\n\t\tupdate()\n\t}\n\n}\n\n```\n\n\n*Rationale* Subclassing in instances where the original class was not built to support subclasses can be a common source of bugs. Marking classes as `final`\nindicates that it was developed under the assumption that it would act on its own without regard for subclasses.\n\n## Operators\n\n### Operator Overloading\n\nOperator overloading is not recommended. Overloads often lead to ambiguous semantics, unintuitive behaviours and obscurities that are difficult for everyone to understand except the person who wrote them. Instead opt for less succinct, yet more descriptive function definitions throughout your code.\n\n### Custom Operators\n\nBe wary of defining entirely new operators, unless your use case specifically requires it. In some situations borrowing an operator that is defined in the standard library of another language makes sense, such as operators specific to high level scientific or mathematical problem solving. The behaviour of your custom operator should be intuitive and obvious. Its semantics should not conflict with existing Swift operators. \n\nWhen defining a custom operator, be clear and use exhaustive documentation. Provide an example use of the operator within your documentation that others will easily understand. Define the new operator in the same file as the type definition that is making use of it.\n\n```swift\n/// Defines a postfix operator used to\n/// add 3 to the value of an integer.\npostfix operator +++\n\n/// Adds a value of 3 to an Integer \n/// by appending the postfix operator.\n///\n/// Eg. let result = 3+++\n/// (result is now 6)\n///\n/// - Parameter n: integer to add 3 to\n/// - Returns: the value of n plus 3\npostfix func +++(n: Int) -\u003e Int {\n    return n + 3\n}\n```\n\nEnsure there is always an existing function available that can be used as an alternative to the custom operator if required. Consumers of your type interface should be able to choose between using your custom operator as a shortcut, or using the function for further clarity.\n\n## Documentation\n\nWell documented code is critical to help other developers understand what the code is doing. Every **open**, **public** and **internal** types should be documented.\nAdditionally developers should annotate any private piece of code when its behavior is not trivial using the regular comment syntax `//`.\n\nSee our [best practices](BestPractices.md#documentation) about documenting the code.\n\n*Rationale* A code without documentation is harder to understand, it is a good practice to document your code to help other developers understand the project, especially when it contains public APIs.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fprolificinteractive%2Fswift-style-guide","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fprolificinteractive%2Fswift-style-guide","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fprolificinteractive%2Fswift-style-guide/lists"}