You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
This repository was archived by the owner on Aug 8, 2023. It is now read-only.
Copy file name to clipboardExpand all lines: swift/README.md
+58-70Lines changed: 58 additions & 70 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -15,7 +15,6 @@ Our overarching goals are conciseness, readability, and simplicity.
15
15
*[Prose](#prose)
16
16
*[Selectors](#selectors)
17
17
*[Generics](#generics)
18
-
*[Class Prefixes](#class-prefixes)
19
18
*[Language](#language)
20
19
*[Code Organization](#code-organization)
21
20
*[Protocol Conformance](#protocol-conformance)
@@ -43,6 +42,7 @@ Our overarching goals are conciseness, readability, and simplicity.
43
42
*[Extending Lifetime](#extending-lifetime)
44
43
*[Access Control](#access-control)
45
44
*[Control Flow](#control-flow)
45
+
*[Error Handling](#error-handling)
46
46
*[Golden Path](#golden-path)
47
47
*[Failing Guards](#failing-guards)
48
48
*[Semicolons](#semicolons)
@@ -60,10 +60,6 @@ Consider warnings to be errors. This rule informs many stylistic decisions such
60
60
61
61
## Naming
62
62
63
-
Clarity at the point of use is your most important goal. Entities such as methods and properties are declared only once but used repeatedly. Design APIs to make those uses clear and concise. When evaluating a design, reading a declaration is seldom sufficient; always examine a use case to make sure it looks clear in context.
64
-
65
-
Clarity is more important than brevity. Although Swift code can be compact, it is a non-goal to enable the smallest possible code with the fewest characters. Brevity in Swift code, where it occurs, is a side-effect of the strong type system and features that naturally reduce boilerplate.
66
-
67
63
Use descriptive names with camel case for classes, methods, variables, etc. Type names (classes, structures, enumerations and protocols) should be capitalized, while method names and variables should start with a lower case letter.
68
64
69
65
**Preferred:**
@@ -92,15 +88,15 @@ Abbreviations and acronyms should generally be avoided. Following the [API Desig
92
88
93
89
**Preferred**
94
90
```swift
95
-
letutf8String: String
96
-
leturlString: URLString
91
+
letutf8Text: String
92
+
lettargetURL: URL
97
93
let userID: UserID
98
94
```
99
95
100
96
**Not Preferred**
101
97
```swift
102
-
letUTF8String: String
103
-
letuRLString: UrlString
98
+
letUTF8Text: String
99
+
letuRLText: UrlString
104
100
let userId: UserId
105
101
```
106
102
@@ -157,16 +153,6 @@ When referring to functions in comments include the required parameter names fro
157
153
158
154
This is the same as the `#selector` syntax. When in doubt, look at how Xcode lists the method in the jump bar – our style here matches that.
159
155
160
-
### Class Prefixes
161
-
162
-
Swift types are automatically namespaced by the module that contains them and you should not add a class prefix such as MOB. 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.
163
-
164
-
```swift
165
-
importSomeModule
166
-
167
-
let myClass = MyModule.UsefulClass()
168
-
```
169
-
170
156
### Selectors
171
157
172
158
Selectors are Obj-C methods that act as handlers for many Cocoa and Cocoa Touch APIs. Prior to Swift 2.2, they were specified using type unsafe strings. This now causes a compiler warning. The "Fix it" button replaces these strings with the **fully qualified** type safe selector. Often, however, you can use context to shorten the expression. This is the preferred style.
@@ -254,6 +240,13 @@ For UIKit view controllers, consider grouping lifecycle, custom accessors, and I
254
240
255
241
Unused (dead) code, including Xcode template code and placeholder comments should be removed. Aspirational methods whose implementation simply calls the super class should also be removed.
Keep imports minimal. For example, don't import `UIKit` when importing `Foundation` will suffice.
@@ -360,7 +346,8 @@ Here's an example of a well-styled class definition:
360
346
361
347
```swift
362
348
classCircle: Shape {
363
-
var x: Int, y: Int
349
+
var x: Int
350
+
var y: Int
364
351
var radius: Double
365
352
var diameter: Double {
366
353
get {
@@ -406,7 +393,7 @@ The example above demonstrates the following style guidelines:
406
393
407
394
For conciseness, avoid using `self` since Swift does not require it to access an object's properties or invoke its methods.
408
395
409
-
Use `self` when required to differentiate between property names and arguments in initializers, and when referencing properties in closure expressions (as required by the compiler):
396
+
Use `self` when required to differentiate between property names and arguments in initializers, and when referencing properties or methods in closure expressions (as required by the compiler):
410
397
411
398
```swift
412
399
classBoardLocation {
@@ -576,14 +563,14 @@ Always use Swift's native types when available. Swift offers bridging to Objecti
576
563
577
564
**Preferred:**
578
565
```swift
579
-
let width =120.0// Double
580
-
letwidthString= (width as NSNumber).stringValue// String
566
+
let width =120.0// Double
567
+
letlabelText= (width as NSNumber).stringValue// String
**Note:** The advantage of using a case-less enumeration is that it can't accidentally be instantiated and works as a pure namespace.
608
594
@@ -624,55 +610,55 @@ class Component {
624
610
625
611
### Static Methods and Variable Type Properties
626
612
627
-
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.
613
+
Static methods and type properties work similarly to free 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.
628
614
629
615
### Optionals
630
616
631
617
Declare variables and function return types as optional with `?` where a nil value is acceptable.
632
618
633
-
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`. Other cases you shoudl use `!` are:
619
+
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`. Other cases you should use `!` are:
634
620
635
621
- You just assigned to an object where you know initialization can not fail:
636
622
637
-
```swift
638
-
let numberSeven =Int("7")!//Don't do this.
639
-
```
623
+
```swift
624
+
let numberSeven =Int("7")!//Don't do this.
625
+
```
640
626
641
-
In this case, wrap this into a static function and write a test for it:
627
+
In this case, wrap this into a static function and write a test for it:
642
628
643
-
```swift
644
-
extensionInt {
645
-
staticfuncseven() ->Int {
646
-
returnInt("7")!
647
-
}
648
-
}
649
-
```
629
+
```swift
630
+
extensionInt {
631
+
staticfuncseven() ->Int {
632
+
returnInt("7")!
633
+
}
634
+
}
635
+
```
650
636
651
-
```swift
652
-
importXCTest
637
+
```swift
638
+
importXCTest
653
639
654
-
classIntegerTests: XCTestCase {
655
-
functestSeven() {
656
-
XCTAssertEqual(7, Int.seven())
657
-
}
658
-
}
659
-
```
640
+
classIntegerTests: XCTestCase {
641
+
functestSeven() {
642
+
XCTAssertEqual(7, Int.seven())
643
+
}
644
+
}
645
+
```
660
646
661
-
Although the test might seem redundant, because `seven()` returns a non-optional, this ensures that even if in the future someone changes the implementation of `seven()`, it won't get past CI if the explicit unwrapping would fail.
647
+
Although the test might seem redundant, because `seven()` returns a non-optional, this ensures that even if in the future someone changes the implementation of `seven()`, it won't get past CI if the explicit unwrapping would fail.
662
648
663
649
- You are creating an object during initialization but need to pass `self` to that object's initializer:
664
650
665
-
```swift
666
-
classComponent: ParentComponent {
667
-
var controller: CustomViewController!// We want to use it as a non-optional but have to initialize after super.init()
651
+
```swift
652
+
classComponent: ParentComponent {
653
+
var controller: CustomViewController!// We want to use it as a non-optional but have to initialize after super.init()
When accessing an optional value, use optional chaining if the value is only accessed once or if there are many optionals in the chain:
678
664
@@ -771,12 +757,12 @@ let maximumWidth: CGFloat = 106.5
771
757
```swift
772
758
let message: String="Click the button"
773
759
let currentBounds: CGRect =computeViewBounds()
774
-
let names= [String]()
760
+
let names: [String] = ["Mic", "Sam", "Christine"]
775
761
```
776
762
777
763
#### Type Annotation for Empty Arrays and Dictionaries
778
764
779
-
For empty arrays and dictionaries, use type annotation. (For an array or dictionary assigned to a large, multi-line literal, use type annotation.)
765
+
For empty arrays and dictionaries, use type annotation. (For an array or dictionary assigned to a large, multi-line literal, use type annotation to make it clear what type(s) the array/dictionary contains)
780
766
781
767
**Preferred:**
782
768
```swift
@@ -873,7 +859,9 @@ resource.request().onComplete { [weak self] response in
873
859
874
860
## Access Control
875
861
876
-
Full access control annotation in tutorials can distract from the main topic and is not required. Using `private` appropriately, however, adds clarity and promotes encapsulation. Use `private` as the leading property specifier. The only things that should come before access control are the `static` specifier or attributes such as `@IBAction` and `@IBOutlet`.
862
+
Using `private` appropriately adds clarity and promotes encapsulation. Use `private` as the leading property specifier. The only things that should come before access control are the `static` specifier or attributes such as `@IBAction` and `@IBOutlet`.
863
+
864
+
An exception to this is RPC methods within Astro, which should be marked as `internal`.
877
865
878
866
**Preferred:**
879
867
```swift
@@ -929,6 +917,8 @@ while i < attendeeList.count {
929
917
}
930
918
```
931
919
920
+
## Error Handling
921
+
932
922
As of Swift 2.0 exceptions have been introduced into the language and the APIs that formerly used `someMethod(..., error: *NSError)` make use of them. We have decided to stick with our existing pattern for returning errors.
933
923
934
924
We typically use an enumeration type:
@@ -1024,8 +1014,6 @@ Swift does not require a semicolon after each statement in your code. They are o
1024
1014
1025
1015
Do not write multiple statements on a single line separated with semicolons.
1026
1016
1027
-
The only exception to this rule is the `for-conditional-increment` construct, which requires semicolons. However, alternative `for-in` constructs should be used where possible.
0 commit comments