├── README.markdown ├── screens ├── indentation.png ├── project_settings.png └── xcode-jump-bar.png └── swiftlint.yml /README.markdown: -------------------------------------------------------------------------------- 1 | # The Official raywenderlich.com Swift Style Guide. 2 | 3 | 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. 4 | 5 | Our overarching goals are clarity, consistency and brevity, in that order. 6 | 7 | ## Table of Contents 8 | 9 | * [Correctness](#correctness) 10 | * [Page guide](#page-guide) 11 | * [Naming](#naming) 12 | * [Prose](#prose) 13 | * [Booleans](#booleans) 14 | * [Delegates](#delegates) 15 | * [Use Type Inferred Context](#use-type-inferred-context) 16 | * [Generics](#generics) 17 | * [Class Prefixes](#class-prefixes) 18 | * [Language](#language) 19 | * [Code Organization](#code-organization) 20 | * [Protocol Conformance](#protocol-conformance) 21 | * [Unused Code](#unused-code) 22 | * [Minimal Imports](#minimal-imports) 23 | * [Spacing](#spacing) 24 | * [Comments](#comments) 25 | * [Classes and Structures](#classes-and-structures) 26 | * [Use of Self](#use-of-self) 27 | * [Protocol Conformance](#protocol-conformance) 28 | * [Computed Properties](#computed-properties) 29 | * [Final](#final) 30 | * [Function Declarations](#function-declarations) 31 | * [Function Calls](#function-calls) 32 | * [Closure Expressions](#closure-expressions) 33 | * [Types](#types) 34 | * [Constants](#constants) 35 | * [Static Methods and Variable Type Properties](#static-methods-and-variable-type-properties) 36 | * [Optionals](#optionals) 37 | * [Lazy Initialization](#lazy-initialization) 38 | * [Type Inference](#type-inference) 39 | * [Syntactic Sugar](#syntactic-sugar) 40 | * [Arrays and Dictionaries](#arrays-and-dictionaries) 41 | * [Functions vs Methods](#functions-vs-methods) 42 | * [Memory Management](#memory-management) 43 | * [Extending Lifetime](#extending-lifetime) 44 | * [Access Control](#access-control) 45 | * [Control Flow](#control-flow) 46 | * [Ternary Operator](#ternary-operator) 47 | * [Golden Path](#golden-path) 48 | * [Failing Guards](#failing-guards) 49 | * [Semicolons](#semicolons) 50 | * [Parentheses](#parentheses) 51 | * [Multi-line String Literals](#multi-line-string-literals) 52 | * [No Emoji](#no-emoji) 53 | * [No #imageLiteral or #colorLiteral](#no-imageliteral-or-colorliteral) 54 | * [Organization and Bundle Identifier](#organization-and-bundle-identifier) 55 | * [References](#references) 56 | 57 | 58 | ## Correctness 59 | 60 | Strive to make your code compile without warnings. This rule informs many style decisions such as using `#selector` types instead of string literals. 61 | 62 | ## Page guide 63 | 64 | Setup page guide in Xcode for 120 symbols. This number is recommended in swiftlint settings. So all code should be inside this page guide. 65 | 66 | ## Naming 67 | 68 | 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: 69 | 70 | - striving for clarity at the call site 71 | - prioritizing clarity over brevity 72 | - using `camelCase` (not `snake_case`) 73 | - using `UpperCamelCase` for types and protocols, `lowerCamelCase` for everything else 74 | - including all needed words while omitting needless words 75 | - using names based on roles, not types 76 | - sometimes compensating for weak type information 77 | - striving for fluent usage 78 | - beginning factory methods with `make` 79 | - naming methods for their side effects 80 | - verb methods follow the -ed, -ing rule for the non-mutating version 81 | - noun methods follow the formX rule for the mutating version 82 | - boolean types should read like assertions 83 | - protocols that describe _what something is_ should read as nouns 84 | - protocols that describe _a capability_ should end in _-able_ or _-ible_ 85 | - using terms that don't surprise experts or confuse beginners 86 | - generally avoiding abbreviations 87 | - using precedent for names 88 | - preferring methods and properties to free functions 89 | - casing acronyms and initialisms uniformly up or down 90 | - giving the same base name to methods that share the same meaning 91 | - avoiding overloads on return type 92 | - choosing good parameter names that serve as documentation 93 | - preferring to name the first parameter instead of including its name in the method name, except as mentioned under Delegates 94 | - labeling closure and tuple parameters 95 | - taking advantage of default parameters 96 | 97 | ### Prose 98 | 99 | When referring to methods in prose, being unambiguous is critical. To refer to a method name, use the simplest form possible. 100 | 101 | 1. Write the method name with no parameters. **Example:** Next, you need to call `addTarget`. 102 | 2. Write the method name with argument labels. **Example:** Next, you need to call `addTarget(_:action:)`. 103 | 3. Write the full method name with argument labels and types. **Example:** Next, you need to call `addTarget(_: Any?, action: Selector?)`. 104 | 105 | For the above example using `UIGestureRecognizer`, 1 is unambiguous and preferred. 106 | 107 | **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. 108 | 109 | ![Methods in Xcode jump bar](screens/xcode-jump-bar.png) 110 | 111 | ### Booleans 112 | 113 | For boolean variables use auxiliary verb at the beginning. 114 | 115 | **Preferred:** 116 | 117 | ```swift 118 | var isFavoriteCategoryFilled: Bool 119 | var hasRoaming: Bool 120 | var isBlocked: Bool 121 | ``` 122 | 123 | **Not Preferred:** 124 | 125 | ```swift 126 | var favoriteCategoryFilled: Bool 127 | var roaming: Bool 128 | var blocked: Bool 129 | ``` 130 | 131 | ### Class Prefixes 132 | 133 | 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. 134 | 135 | ```swift 136 | import SomeModule 137 | 138 | let myClass = MyModule.UsefulClass() 139 | ``` 140 | 141 | ### Delegates 142 | 143 | When creating custom delegate methods, an unnamed first parameter should be the delegate source. (UIKit contains numerous examples of this.) 144 | 145 | **Preferred**: 146 | ```swift 147 | func namePickerView(_ namePickerView: NamePickerView, didSelectName name: String) 148 | func namePickerViewShouldReload(_ namePickerView: NamePickerView) -> Bool 149 | ``` 150 | 151 | **Not Preferred**: 152 | ```swift 153 | func didSelectName(namePicker: NamePickerViewController, name: String) 154 | func namePickerShouldReload() -> Bool 155 | ``` 156 | 157 | ### Use Type Inferred Context 158 | 159 | Use compiler inferred context to write shorter, clear code. (Also see [Type Inference](#type-inference).) 160 | 161 | **Preferred**: 162 | ```swift 163 | let selector = #selector(viewDidLoad) 164 | view.backgroundColor = .red 165 | let toView = context.view(forKey: .to) 166 | let view = UIView(frame: .zero) 167 | ``` 168 | 169 | **Not Preferred**: 170 | ```swift 171 | let selector = #selector(ViewController.viewDidLoad) 172 | view.backgroundColor = UIColor.red 173 | let toView = context.view(forKey: UITransitionContextViewKey.to) 174 | let view = UIView(frame: CGRect.zero) 175 | ``` 176 | 177 | ### Generics 178 | 179 | 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`. 180 | 181 | **Preferred**: 182 | ```swift 183 | struct Stack { ... } 184 | func write(to target: inout Target) 185 | func swap(_ a: inout T, _ b: inout T) 186 | ``` 187 | 188 | **Not Preferred**: 189 | ```swift 190 | struct Stack { ... } 191 | func write(to target: inout target) 192 | func swap(_ a: inout Thing, _ b: inout Thing) 193 | ``` 194 | 195 | ### Language 196 | 197 | Use US English spelling to match Apple's API. 198 | 199 | **Preferred**: 200 | ```swift 201 | let color = "red" 202 | ``` 203 | 204 | **Not Preferred**: 205 | ```swift 206 | let colour = "red" 207 | ``` 208 | 209 | ## Code Organization 210 | 211 | 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. 212 | 213 | The next sequence nice to follow: 214 | 215 | ```swift 216 | // MARK: - Types 217 | 218 | // MARK: - Constants 219 | 220 | // MARK: - Public Properties 221 | 222 | // MARK: - IBOutlet 223 | 224 | // MARK: - Private Properties 225 | 226 | // MARK: - Initializers 227 | 228 | // MARK: - UIViewController(*) 229 | 230 | // MARK: - Public Methods 231 | 232 | // MARK: - IBAction 233 | 234 | // MARK: - Private Methods 235 | 236 | ``` 237 | > (*)Instead of `UIViewController` you must write other superclass, that methods you override. 238 | 239 | Leave one empty lines between functions and one after `MARK`s. 240 | 241 | **Preferred**: 242 | 243 | ```swift: 244 | // MARK: - Private Methods 245 | 246 | private func retry() { 247 | // ... 248 | } 249 | ``` 250 | 251 | **Not Preferred**: 252 | 253 | ```swift: 254 | // MARK:Constants 255 | enum Constants { 256 | // ... 257 | } 258 | ``` 259 | 260 | ### Protocol Conformance 261 | 262 | 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. 263 | 264 | **Preferred**: 265 | ```swift 266 | class MyViewController: UIViewController { 267 | // class stuff here 268 | } 269 | 270 | // MARK: - UITableViewDataSource 271 | extension MyViewController: UITableViewDataSource { 272 | // table view data source methods 273 | } 274 | 275 | // MARK: - UIScrollViewDelegate 276 | extension MyViewController: UIScrollViewDelegate { 277 | // scroll view delegate methods 278 | } 279 | ``` 280 | 281 | **Not Preferred**: 282 | ```swift 283 | class MyViewController: UIViewController, UITableViewDataSource, UIScrollViewDelegate { 284 | // all methods 285 | } 286 | ``` 287 | 288 | > This rule doesn't work for two cases: 289 | > - When you need override method which implemented in extension (Declarations in extensions cannot override yet) 290 | > - When you use class with generic and Objective C protocols with optional methods (@objc is not supported within extensions of generic classes or classes that inherit from generic classes) 291 | 292 | 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. 293 | 294 | For UIKit view controllers, consider grouping lifecycle, custom accessors, and IBAction in separate class extensions. 295 | 296 | ### Unused Code 297 | 298 | 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. 299 | 300 | 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. 301 | 302 | **Preferred**: 303 | ```swift 304 | override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 305 | Database.contacts.count 306 | } 307 | ``` 308 | 309 | **Not Preferred**: 310 | ```swift 311 | override func didReceiveMemoryWarning() { 312 | super.didReceiveMemoryWarning() 313 | // Dispose of any resources that can be recreated. 314 | } 315 | 316 | override func numberOfSections(in tableView: UITableView) -> Int { 317 | // #warning Incomplete implementation, return the number of sections 318 | return 1 319 | } 320 | 321 | override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 322 | // #warning Incomplete implementation, return the number of rows 323 | return Database.contacts.count 324 | } 325 | 326 | ``` 327 | ### Minimal Imports 328 | 329 | 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`. 330 | 331 | **Preferred**: 332 | ```swift 333 | import UIKit 334 | var view: UIView 335 | let defaultSession: URLSession 336 | ``` 337 | 338 | ```swift 339 | import Foundation 340 | let defaultSession: URLSession 341 | ``` 342 | 343 | **Not Preferred**: 344 | ```swift 345 | import Foundation 346 | import UIKit 347 | var view: UIView 348 | let defaultSession: URLSession 349 | ``` 350 | 351 | ```swift 352 | import UIKit 353 | let defaultSession: URLSession 354 | ``` 355 | 356 | ## Spacing 357 | 358 | * Indent using 4 spaces rather than tabs to conserve space and help prevent line wrapping. 359 | 360 | * 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. 361 | * 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. 362 | 363 | **Preferred**: 364 | ```swift 365 | if user.isHappy { 366 | // Do something 367 | } else { 368 | // Do something else 369 | } 370 | ``` 371 | 372 | **Not Preferred**: 373 | ```swift 374 | if user.isHappy 375 | { 376 | // Do something 377 | } 378 | else { 379 | // Do something else 380 | } 381 | ``` 382 | 383 | * 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. 384 | 385 | **Preferred**: 386 | ```swift 387 | let user = try await getUser( 388 | for: userID, 389 | on: connection 390 | ) 391 | ``` 392 | 393 | **Not Preferred**: 394 | ```swift 395 | let user = try await getUser( 396 | for: userID, 397 | on: connection) 398 | ``` 399 | 400 | * 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:)`. 401 | 402 | **Preferred**: 403 | ```swift 404 | class TestDatabase: Database { 405 | var data: [String: CGFloat] = ["A": 1.2, "B": 3.2] 406 | } 407 | ``` 408 | 409 | **Not Preferred**: 410 | ```swift 411 | class TestDatabase : Database { 412 | var data :[String:CGFloat] = ["A" : 1.2, "B":3.2] 413 | } 414 | ``` 415 | 416 | * Long lines should be wrapped at around 70 characters. A hard limit is intentionally not specified. 417 | 418 | * Avoid trailing whitespaces at the ends of lines. 419 | 420 | * Add a single newline character at the end of each file. 421 | 422 | ## Comments 423 | 424 | 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. 425 | 426 | 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._ 427 | 428 | ## Classes and Structures 429 | 430 | ### Which one to use? 431 | 432 | 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. 433 | 434 | 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. 435 | 436 | 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. 437 | 438 | ### Example definition 439 | 440 | Here's an example of a well-styled class definition: 441 | 442 | ```swift 443 | class Circle: Shape { 444 | var x: Int, y: Int 445 | var radius: Double 446 | var diameter: Double { 447 | get { 448 | radius * 2 449 | } 450 | set { 451 | radius = newValue / 2 452 | } 453 | } 454 | 455 | init(x: Int, y: Int, radius: Double) { 456 | self.x = x 457 | self.y = y 458 | self.radius = radius 459 | } 460 | 461 | convenience init(x: Int, y: Int, diameter: Double) { 462 | self.init(x: x, y: y, radius: diameter / 2) 463 | } 464 | 465 | override func area() -> Double { 466 | Double.pi * radius * radius 467 | } 468 | } 469 | 470 | extension Circle: CustomStringConvertible { 471 | var description: String { 472 | "center = \(centerString) area = \(area())" 473 | } 474 | 475 | private var centerString: String { 476 | "(\(x),\(y))" 477 | } 478 | } 479 | ``` 480 | 481 | When the method signature is too long, parameters should be moved to a new line: 482 | ```swift 483 | override func register( 484 | withСardNumber cardNumber: String, 485 | completion completionBlock: @escaping AuthService.RegisterWithCardNumberCompletionBlock, 486 | failure failureBlock: @escaping Service.ServiceFailureBlock) -> WebTransportOperation { 487 | 488 | // reticulate code goes here 489 | } 490 | ``` 491 | 492 | The example above demonstrates the following style guidelines: 493 | 494 | + 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`. 495 | + Define multiple variables and structures on a single line if they share a common purpose / context. 496 | + Indent getter and setter definitions and property observers. 497 | + Don't add modifiers such as `internal` when they're already the default. Similarly, don't repeat the access modifier when overriding a method. 498 | + Organize extra functionality (e.g. printing) in extensions. 499 | + Hide non-shared, implementation details such as `centerString` inside the extension using `private` access control. 500 | 501 | ### Use of Self 502 | 503 | For conciseness, avoid using `self` since Swift does not require it to access an object's properties or invoke its methods. 504 | 505 | 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. 506 | 507 | 508 | ### Computed Properties 509 | 510 | 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. 511 | 512 | **Preferred**: 513 | ```swift 514 | var diameter: Double { 515 | radius * 2 516 | } 517 | ``` 518 | 519 | **Not Preferred**: 520 | ```swift 521 | var diameter: Double { 522 | get { 523 | radius * 2 524 | } 525 | } 526 | ``` 527 | 528 | Always use computed property instead of method with zero arguments and no side effects. 529 | 530 | **Preferred:** 531 | 532 | ```swift 533 | var homeFolderPath: Path { 534 | //... 535 | return path 536 | } 537 | ``` 538 | 539 | **Not Preferred:** 540 | 541 | ```swift 542 | func homeFolderPath() -> Path { 543 | //... 544 | return path 545 | } 546 | ``` 547 | 548 | ### Final 549 | 550 | Always 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. 551 | 552 | ```swift 553 | // Turn any generic type into a reference type using this Box class. 554 | final class Box { 555 | let value: T 556 | init(_ value: T) { 557 | self.value = value 558 | } 559 | } 560 | ``` 561 | 562 | This is improve yout code reading and speed up compilation. 563 | 564 | ## Function Declarations 565 | 566 | Keep short function declarations on one line including the opening brace: 567 | 568 | ```swift 569 | func reticulateSplines(spline: [Double]) -> Bool { 570 | // reticulate code goes here 571 | } 572 | ``` 573 | 574 | For functions with long signatures, put each parameter on a new line and add an extra indent on subsequent lines: 575 | 576 | ```swift 577 | func reticulateSplines( 578 | spline: [Double], 579 | adjustmentFactor: Double, 580 | translateConstant: Int, 581 | comment: String 582 | ) -> Bool { 583 | // reticulate code goes here 584 | } 585 | ``` 586 | 587 | Don't use `(Void)` to represent the lack of an input; simply use `()`. Use `Void` instead of `()` for closure and function outputs. 588 | 589 | **Preferred**: 590 | 591 | ```swift 592 | func updateConstraints() -> Void { 593 | // magic happens here 594 | } 595 | 596 | typealias CompletionHandler = (result) -> Void 597 | ``` 598 | 599 | **Not Preferred**: 600 | 601 | ```swift 602 | func updateConstraints() -> () { 603 | // magic happens here 604 | } 605 | 606 | typealias CompletionHandler = (result) -> () 607 | ``` 608 | 609 | ## Function Calls 610 | 611 | Mirror the style of function declarations at call sites. Calls that fit on a single line should be written as such: 612 | 613 | ```swift 614 | let success = reticulateSplines(splines) 615 | ``` 616 | 617 | If the call site must be wrapped, put each parameter on a new line, indented one additional level: 618 | 619 | ```swift 620 | let success = reticulateSplines( 621 | spline: splines, 622 | adjustmentFactor: 1.3, 623 | translateConstant: 2, 624 | comment: "normalize the display" 625 | ) 626 | ``` 627 | 628 | ## Closure Expressions 629 | 630 | 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. 631 | 632 | Closure parameter type and parentheses should be omitted. 633 | 634 | **Preferred**: 635 | ```swift 636 | UIView.animate(withDuration: 1.0) { 637 | self.myView.alpha = 0 638 | } 639 | 640 | UIView.animate( 641 | withDuration: 1.0, 642 | animations: { 643 | self.myView.alpha = 0 644 | }, 645 | completion: { finished in 646 | self.myView.removeFromSuperview() 647 | }) 648 | ``` 649 | 650 | **Not Preferred**: 651 | ```swift 652 | UIView.animate(withDuration: 1.0, animations: { 653 | self.myView.alpha = 0 654 | }) 655 | 656 | UIView.animate(withDuration: 1.0, animations: { 657 | self.myView.alpha = 0 658 | }) { f in 659 | self.myView.removeFromSuperview() 660 | } 661 | ``` 662 | 663 | For single-expression closures where the context is clear, use implicit returns: 664 | 665 | ```swift 666 | attendeeList.sort { a, b in 667 | a > b 668 | } 669 | ``` 670 | 671 | 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: 672 | 673 | ```swift 674 | let value = numbers.map { $0 * 2 }.filter { $0 % 3 == 0 }.index(of: 90) 675 | 676 | let value = numbers 677 | .map {$0 * 2} 678 | .filter {$0 > 50} 679 | .map {$0 + 10} 680 | ``` 681 | 682 | ## Types 683 | 684 | 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. 685 | 686 | **Preferred**: 687 | ```swift 688 | let width = 120.0 // Double 689 | let widthString = "\(width)" // String 690 | ``` 691 | 692 | **Less Preferred**: 693 | ```swift 694 | let width = 120.0 // Double 695 | let widthString = (width as NSNumber).stringValue // String 696 | ``` 697 | 698 | **Not Preferred**: 699 | ```swift 700 | let width: NSNumber = 120.0 // NSNumber 701 | let widthString: NSString = width.stringValue // NSString 702 | ``` 703 | 704 | In drawing code, use `CGFloat` if it makes the code more succinct by avoiding too many conversions. 705 | 706 | ### Constants 707 | 708 | 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. 709 | 710 | **Tip:** A good technique is to define everything using `let` and only change it to `var` if the compiler complains! 711 | 712 | 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: 713 | 714 | **Preferred**: 715 | ```swift 716 | enum Math { 717 | static let e = 2.718281828459045235360287 718 | static let root2 = 1.41421356237309504880168872 719 | } 720 | 721 | let hypotenuse = side * Math.root2 722 | 723 | ``` 724 | **Note:** The advantage of using a case-less enumeration is that it can't accidentally be instantiated and works as a pure namespace. 725 | 726 | **Not Preferred**: 727 | ```swift 728 | let e = 2.718281828459045235360287 // pollutes global namespace 729 | let root2 = 1.41421356237309504880168872 730 | 731 | let hypotenuse = side * root2 // what is root2? 732 | ``` 733 | 734 | In case of declaration of single constant use following names 735 | 736 | **Preferred:** 737 | 738 | ```swift 739 | let TopMargin: CGFloat = 10 740 | ``` 741 | 742 | **Not Preferred:** 743 | 744 | ```swift 745 | let kTopMargin: CGFloat = 10 746 | let bottomMargin: CGFloat = 100 747 | ``` 748 | 749 | ### Static Methods and Variable Type Properties 750 | 751 | 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. 752 | 753 | ### Optionals 754 | 755 | Declare variables and function return types as optional with `?` where a `nil` value is acceptable. 756 | 757 | 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. 758 | 759 | When accessing an optional value, use optional chaining if the value is only accessed once or if there are many optionals in the chain: 760 | 761 | ```swift 762 | textContainer?.textLabel?.setNeedsDisplay() 763 | ``` 764 | 765 | Use optional binding when it's more convenient to unwrap once and perform multiple operations: 766 | 767 | ```swift 768 | if let textContainer = textContainer { 769 | // do many things with textContainer 770 | } 771 | ``` 772 | 773 | When naming optional variables and properties, avoid naming them like `optionalString` or `maybeView` since their optional-ness is already in the type declaration. 774 | 775 | For optional binding, shadow the original name whenever possible rather than using names like `unwrappedView` or `actualLabel`. Add new line after `if`, if there are several variables in unwrapping clause. 776 | 777 | **Preferred**: 778 | ```swift 779 | var subview: UIView? 780 | var volume: Double? 781 | 782 | // later on... 783 | if 784 | let subview = subview, 785 | let volume = volume { 786 | // do something with unwrapped subview and volume 787 | } 788 | 789 | // another example 790 | resource.request().onComplete { [weak self] response in 791 | guard let self = self else { return } 792 | let model = self.updateModel(response) 793 | self.updateUI(model) 794 | } 795 | ``` 796 | 797 | **Not Preferred**: 798 | ```swift 799 | var optionalSubview: UIView? 800 | var volume: Double? 801 | 802 | if let unwrappedSubview = optionalSubview { 803 | if let realVolume = volume { 804 | // do something with unwrappedSubview and realVolume 805 | } 806 | } 807 | 808 | // another example 809 | UIView.animate(withDuration: 2.0) { [weak self] in 810 | guard let strongSelf = self else { return } 811 | strongSelf.alpha = 1.0 812 | } 813 | ``` 814 | 815 | ### Lazy Initialization 816 | 817 | 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: 818 | 819 | ```swift 820 | lazy var locationManager = makeLocationManager() 821 | 822 | private func makeLocationManager() -> CLLocationManager { 823 | let manager = CLLocationManager() 824 | manager.desiredAccuracy = kCLLocationAccuracyBest 825 | manager.delegate = self 826 | manager.requestAlwaysAuthorization() 827 | return manager 828 | } 829 | ``` 830 | 831 | **Notes:** 832 | - `[unowned self]` is not required here. A retain cycle is not created. 833 | - Location manager has a side-effect for popping up UI to ask the user for permission so fine grain control makes sense here. 834 | 835 | 836 | ### Type Inference 837 | 838 | 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`. 839 | 840 | **Preferred**: 841 | ```swift 842 | let message = "Click the button" 843 | let currentBounds = computeViewBounds() 844 | var names = ["Mic", "Sam", "Christine"] 845 | let maximumWidth: CGFloat = 106.5 846 | ``` 847 | 848 | **Not Preferred**: 849 | ```swift 850 | let message: String = "Click the button" 851 | let currentBounds: CGRect = computeViewBounds() 852 | var names = [String]() 853 | ``` 854 | 855 | #### Type Annotation for Empty Arrays and Dictionaries 856 | 857 | For empty arrays and dictionaries, use type annotation. (For an array or dictionary assigned to a large, multi-line literal, use type annotation.) 858 | 859 | **Preferred**: 860 | ```swift 861 | var names: [String] = [] 862 | var lookup: [String: Int] = [:] 863 | ``` 864 | 865 | **Not Preferred**: 866 | ```swift 867 | var names = [String]() 868 | var lookup = [String: Int]() 869 | ``` 870 | 871 | **NOTE**: Following this guideline means picking descriptive names is even more important than before. 872 | 873 | 874 | ### Syntactic Sugar 875 | 876 | Prefer the shortcut versions of type declarations over the full generics syntax. 877 | 878 | **Preferred**: 879 | ```swift 880 | var deviceModels: [String] 881 | var employees: [Int: String] 882 | var faxNumber: Int? 883 | ``` 884 | 885 | **Not Preferred**: 886 | ```swift 887 | var deviceModels: Array 888 | var employees: Dictionary 889 | var faxNumber: Optional 890 | ``` 891 | 892 | ### Arrays and Dictionaries 893 | 894 | Use the following carrying when array or dictionary go over page guide. 895 | 896 | **Preferred:** 897 | 898 | ```swift 899 | let deviceModels = ["BMW": 100, "Mercedes": 120] 900 | let wheels = [ 901 | "Continental", 902 | "Vitoria", 903 | ... 904 | ] 905 | ``` 906 | 907 | **Not Preferred:** 908 | 909 | ```swift 910 | let wheels = ["Continental", "Vitoria", // to many over page guide] 911 | ``` 912 | 913 | ## Functions vs Methods 914 | 915 | 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. 916 | 917 | Free functions are most appropriate when they aren't associated with any particular type or instance. 918 | 919 | **Preferred** 920 | ```swift 921 | let sorted = items.mergeSorted() // easily discoverable 922 | rocket.launch() // acts on the model 923 | ``` 924 | 925 | **Not Preferred** 926 | ```swift 927 | let sorted = mergeSort(items) // hard to discover 928 | launch(&rocket) 929 | ``` 930 | 931 | **Free Function Exceptions** 932 | ```swift 933 | let tuples = zip(a, b) // feels natural as a free function (symmetry) 934 | let value = max(x, y, z) // another free function that feels natural 935 | ``` 936 | 937 | ## Memory Management 938 | 939 | 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. 940 | 941 | ### Extending object lifetime 942 | 943 | 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. 944 | 945 | **Preferred** 946 | ```swift 947 | resource.request().onComplete { [weak self] response in 948 | guard let self = self else { return } 949 | let model = self.updateModel(response) 950 | self.updateUI(model) 951 | } 952 | ``` 953 | 954 | **Not Preferred** 955 | ```swift 956 | // might crash if self is released before response returns 957 | resource.request().onComplete { [unowned self] response in 958 | let model = self.updateModel(response) 959 | self.updateUI(model) 960 | } 961 | ``` 962 | 963 | **Not Preferred** 964 | ```swift 965 | // deallocate could happen between updating the model and updating UI 966 | resource.request().onComplete { [weak self] response in 967 | let model = self?.updateModel(response) 968 | self?.updateUI(model) 969 | } 970 | ``` 971 | 972 | ## Access Control 973 | 974 | 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. 975 | 976 | Only explicitly use `open`, `public`, and `internal` when you require a full access control specification. 977 | 978 | 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`. 979 | 980 | **Preferred**: 981 | ```swift 982 | private let message = "Great Scott!" 983 | 984 | class TimeMachine { 985 | private dynamic lazy var fluxCapacitor = FluxCapacitor() 986 | } 987 | ``` 988 | 989 | **Not Preferred**: 990 | ```swift 991 | fileprivate let message = "Great Scott!" 992 | 993 | class TimeMachine { 994 | lazy dynamic private var fluxCapacitor = FluxCapacitor() 995 | } 996 | ``` 997 | 998 | ## Control Flow 999 | 1000 | Prefer the `for-in` style of `for` loop over the `while-condition-increment` style. 1001 | 1002 | **Preferred**: 1003 | ```swift 1004 | for _ in 0..<3 { 1005 | print("Hello three times") 1006 | } 1007 | 1008 | for (index, person) in attendeeList.enumerated() { 1009 | print("\(person) is at position #\(index)") 1010 | } 1011 | 1012 | for index in stride(from: 0, to: items.count, by: 2) { 1013 | print(index) 1014 | } 1015 | 1016 | for index in (0...3).reversed() { 1017 | print(index) 1018 | } 1019 | ``` 1020 | 1021 | **Not Preferred**: 1022 | ```swift 1023 | var i = 0 1024 | while i < 3 { 1025 | print("Hello three times") 1026 | i += 1 1027 | } 1028 | 1029 | 1030 | var i = 0 1031 | while i < attendeeList.count { 1032 | let person = attendeeList[i] 1033 | print("\(person) is at position #\(i)") 1034 | i += 1 1035 | } 1036 | ``` 1037 | 1038 | ### Ternary Operator 1039 | 1040 | 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. 1041 | 1042 | **Preferred**: 1043 | 1044 | ```swift 1045 | let value = 5 1046 | result = value != 0 ? x : y 1047 | 1048 | let isHorizontal = true 1049 | result = isHorizontal ? x : y 1050 | 1051 | let isMultiplyLine = true 1052 | result = isMultiplyLine ? 1053 | x : 1054 | y 1055 | ``` 1056 | 1057 | **Not Preferred**: 1058 | 1059 | ```swift 1060 | result = a > b ? x = c > d ? c : d : y 1061 | ``` 1062 | 1063 | ## Golden Path 1064 | 1065 | 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. 1066 | 1067 | **Preferred**: 1068 | ```swift 1069 | func computeFFT(context: Context?, inputData: InputData?) throws -> Frequencies { 1070 | guard let context = context else { 1071 | throw FFTError.noContext 1072 | } 1073 | guard let inputData = inputData else { 1074 | throw FFTError.noInputData 1075 | } 1076 | 1077 | // use context and input to compute the frequencies 1078 | return frequencies 1079 | } 1080 | ``` 1081 | 1082 | **Not Preferred**: 1083 | ```swift 1084 | func computeFFT(context: Context?, inputData: InputData?) throws -> Frequencies { 1085 | if let context = context { 1086 | if let inputData = inputData { 1087 | // use context and input to compute the frequencies 1088 | 1089 | return frequencies 1090 | } else { 1091 | throw FFTError.noInputData 1092 | } 1093 | } else { 1094 | throw FFTError.noContext 1095 | } 1096 | } 1097 | ``` 1098 | 1099 | 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. Example: 1100 | 1101 | **Preferred**: 1102 | ```swift 1103 | guard 1104 | let number1 = number1, 1105 | let number2 = number2, 1106 | let number3 = number3 1107 | else { 1108 | fatalError("impossible") 1109 | } 1110 | // do something with numbers 1111 | ``` 1112 | 1113 | or you can use one-liner with one `else` operation 1114 | 1115 | ```swift 1116 | guard 1117 | let number1 = number1, 1118 | let number2 = number2 1119 | else { return } 1120 | // do something with numbers 1121 | ``` 1122 | 1123 | or one-liner with one condition 1124 | 1125 | ```swift 1126 | guard let number1 = number1 else { return } 1127 | ``` 1128 | 1129 | **Not Preferred**: 1130 | ```swift 1131 | if let number1 = number1 { 1132 | if let number2 = number2 { 1133 | if let number3 = number3 { 1134 | // do something with numbers 1135 | } else { 1136 | fatalError("impossible") 1137 | } 1138 | } else { 1139 | fatalError("impossible") 1140 | } 1141 | } else { 1142 | fatalError("impossible") 1143 | } 1144 | ``` 1145 | 1146 | ### For if let: 1147 | 1148 | **Preferred**: 1149 | 1150 | ```swift 1151 | if isTrue(), 1152 | isFalse(), 1153 | tax > MinTax { 1154 | // ... 1155 | } 1156 | ``` 1157 | 1158 | **Not preferred**: 1159 | 1160 | ```swift 1161 | if a > b && b > c && tax > MinTax && currentValue > MaxValue { 1162 | // ... 1163 | } 1164 | ``` 1165 | 1166 | ### Failing Guards 1167 | 1168 | 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. 1169 | 1170 | ## Semicolons 1171 | 1172 | 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. 1173 | 1174 | Do not write multiple statements on a single line separated with semicolons. 1175 | 1176 | **Preferred**: 1177 | ```swift 1178 | let swift = "not a scripting language" 1179 | ``` 1180 | 1181 | **Not Preferred**: 1182 | ```swift 1183 | let swift = "not a scripting language"; 1184 | ``` 1185 | 1186 | **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) 1187 | 1188 | ## Parentheses 1189 | 1190 | Parentheses around conditionals are not required and should be omitted. 1191 | 1192 | **Preferred**: 1193 | ```swift 1194 | if name == "Hello" { 1195 | print("World") 1196 | } 1197 | ``` 1198 | 1199 | **Not Preferred**: 1200 | ```swift 1201 | if (name == "Hello") { 1202 | print("World") 1203 | } 1204 | ``` 1205 | 1206 | In larger expressions, optional parentheses can sometimes make code read more clearly. 1207 | 1208 | **Preferred**: 1209 | ```swift 1210 | let playerMark = (player == current ? "X" : "O") 1211 | ``` 1212 | 1213 | ## Multi-line String Literals 1214 | 1215 | 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. 1216 | 1217 | **Preferred**: 1218 | 1219 | ```swift 1220 | let message = """ 1221 | You cannot charge the flux \ 1222 | capacitor with a 9V battery. 1223 | You must use a super-charger \ 1224 | which costs 10 credits. You currently \ 1225 | have \(credits) credits available. 1226 | """ 1227 | ``` 1228 | 1229 | **Not Preferred**: 1230 | 1231 | ```swift 1232 | let message = """You cannot charge the flux \ 1233 | capacitor with a 9V battery. 1234 | You must use a super-charger \ 1235 | which costs 10 credits. You currently \ 1236 | have \(credits) credits available. 1237 | """ 1238 | ``` 1239 | 1240 | **Not Preferred**: 1241 | 1242 | ```swift 1243 | let message = "You cannot charge the flux " + 1244 | "capacitor with a 9V battery.\n" + 1245 | "You must use a super-charger " + 1246 | "which costs 10 credits. You currently " + 1247 | "have \(credits) credits available." 1248 | ``` 1249 | 1250 | ## No Emoji 1251 | 1252 | 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. 1253 | 1254 | ## No #imageLiteral or #colorLiteral 1255 | 1256 | 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:)`. 1257 | 1258 | ## Organization and Bundle Identifier 1259 | 1260 | Where an Xcode project is involved, the organization should be set to `Redmadrobot` and the Bundle Identifier set to `com.redmadrobot.ProjectName` where `ProjectName` is the name of your project. 1261 | 1262 | ![Xcode Project settings](screens/project_settings.png) 1263 | 1264 | ## References 1265 | 1266 | * [The Swift API Design Guidelines](https://swift.org/documentation/api-design-guidelines/) 1267 | * [The Swift Programming Language](https://developer.apple.com/library/prerelease/ios/documentation/swift/conceptual/swift_programming_language/index.html) 1268 | * [Using Swift with Cocoa and Objective-C](https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/BuildingCocoaApps/index.html) 1269 | * [Swift Standard Library Reference](https://developer.apple.com/library/prerelease/ios/documentation/General/Reference/SwiftStandardLibraryReference/index.html) 1270 | -------------------------------------------------------------------------------- /screens/indentation.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RedMadRobot/RMR-swift-style-guide/263745f79c9fafbb02027b4910157dbd06b3cf5e/screens/indentation.png -------------------------------------------------------------------------------- /screens/project_settings.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RedMadRobot/RMR-swift-style-guide/263745f79c9fafbb02027b4910157dbd06b3cf5e/screens/project_settings.png -------------------------------------------------------------------------------- /screens/xcode-jump-bar.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RedMadRobot/RMR-swift-style-guide/263745f79c9fafbb02027b4910157dbd06b3cf5e/screens/xcode-jump-bar.png -------------------------------------------------------------------------------- /swiftlint.yml: -------------------------------------------------------------------------------- 1 | disabled_rules: 2 | - trailing_whitespace # Lines should not have trailing whitespace. 3 | - force_unwrapping # Force unwrapping should be avoided. 4 | - implicit_return # Implicit return should not be a strict rule. 5 | 6 | opt_in_rules: 7 | - closure_end_indentation # Closure end should have the same indentation as the line that started it. 8 | - closure_spacing # Closure expressions should have a single space inside each brace. 9 | - operator_usage_whitespace # Operators should be surrounded by a single whitespace when they are being used. 10 | - explicit_init # Explicitly calling .init() should be avoided. 11 | - first_where # Prefer using .first(where:) over .filter { }.first in collections. 12 | - redundant_nil_coalescing # nil coalescing operator is only evaluated if the lhs is nil, coalescing operator with nil as rhs is redundant 13 | - single_test_class # Test files should contain a single QuickSpec or XCTestCase class. 14 | - sorted_imports # Imports should be sorted. 15 | - switch_case_on_newline # Cases inside a switch should always be on a newline 16 | - object_literal # Prefer object literals over image and color inits. 17 | - overridden_super_call # Some overridden methods should always call super 18 | - unused_optional_binding # Prefer != nil over let _ = 19 | - empty_count # Prefer checking isEmpty over comparing count to zero. 20 | - multiline_parameters # Functions and methods parameters should be either on the same line, or one per line. 21 | - unneeded_parentheses_in_closure_argument # Parentheses are not needed when declaring closure arguments. 22 | - vertical_parameter_alignment_on_call # Function parameters should be aligned vertically if they’re in multiple lines in a method call. 23 | - private_outlet # IBOutlets should be private to avoid leaking UIKit to higher layers. 24 | - private_action # IBActions should be private. 25 | 26 | excluded: 27 | - vendor 28 | - Pods 29 | - DAOGenerator 30 | - ParserGenerator 31 | - ServiceGenerator 32 | # Добавить пути на другие сгенерированные классы – цвета/модели/шрифты 33 | 34 | identifier_name: 35 | min_length: 1 36 | max_length: 60 37 | 38 | type_body_length: 39 | warning: 600 40 | error: 800 41 | 42 | file_length: 43 | warning: 1000 44 | error: 1200 45 | 46 | line_length: 47 | error: 120 48 | ignores_urls: true 49 | ignores_comments: true 50 | 51 | function_body_length: 52 | warning: 40 53 | error: 120 54 | 55 | function_parameter_count: 56 | error: 10 57 | 58 | large_tuple: 59 | warning: 5 60 | error: 5 61 | 62 | cyclomatic_complexity: 63 | warning: 10 64 | error: 40 65 | 66 | type_name: 67 | max_length: 68 | warning: 60 69 | error: 100 70 | 71 | force_cast: 72 | warning 73 | 74 | control_statement: 75 | error 76 | 77 | implicit_getter: 78 | error 79 | 80 | vertical_parameter_alignment: 81 | error 82 | 83 | return_arrow_whitespace: 84 | error 85 | 86 | unneeded_break_in_switch: 87 | error 88 | 89 | syntactic_sugar: 90 | error 91 | 92 | redundant_optional_initialization: 93 | error 94 | 95 | custom_rules: 96 | mark_without_minus_sign: 97 | regex: "(\\/\\/ )+([MARK])\\w+\\:+\\ +(?!-)" 98 | service_layer_injection: 99 | name: "Service layer DI" 100 | regex: "(ServiceLayer\\.shared\\.\\w+\\.)|(ServiceLayer\\.shared\\s+)" 101 | match_kinds: 102 | - identifier 103 | message: "Pass the services as dependencies via init" 104 | --------------------------------------------------------------------------------