├── screens ├── indentation.png ├── xcode-jump-bar.png └── project_settings.png ├── ko_style_guide.md └── README.markdown /screens/indentation.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swift-kr/swift-style-guide-raywenderlich/HEAD/screens/indentation.png -------------------------------------------------------------------------------- /screens/xcode-jump-bar.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swift-kr/swift-style-guide-raywenderlich/HEAD/screens/xcode-jump-bar.png -------------------------------------------------------------------------------- /screens/project_settings.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/swift-kr/swift-style-guide-raywenderlich/HEAD/screens/project_settings.png -------------------------------------------------------------------------------- /ko_style_guide.md: -------------------------------------------------------------------------------- 1 | # raywenderlich.com 공식 Swift 스타일 가이드 2 | 3 | 이 스타일가이드는 다른 것들과는 다소 차이가 있을 수 있습니다. 4 | 왜냐하면, 출판물 및 웹용 가독성을 중점을 두고 있기 때문입니다. 5 | raywenderlich.com에는 많은 저자들이 모여 있지만, 책, 튜토리얼, 시작킷트에서 일관성이 있는 코드를 유지하기 위해 이 스타일 가이드를 작성했습니다. 6 | 7 | 큰 틀의 지침서를 목표로 간결하고 가독성이 좋고 단순하게 만들기 위함입니다. 8 | 9 | Objective-C 코딩 지침서를 여기를 참고하세요。 10 | [Objective-C 스타일 가이드](https://github.com/raywenderlich/objective-c-style-guide) 11 | 12 | ## Table of Contents 13 | 14 | * [Naming](#naming) 15 | * [Class Prefixes](#class-prefixes) 16 | * [Spacing](#spacing) 17 | * [Comments](#comments) 18 | * [Classes and Structures](#classes-and-structures) 19 | * [Use of Self](#use-of-self) 20 | * [Function Declarations](#function-declarations) 21 | * [Closures](#closures) 22 | * [Types](#types) 23 | * [Constants](#constants) 24 | * [Optionals](#optionals) 25 | * [Struct Initializers](#struct-initializers) 26 | * [Type Inference](#type-inference) 27 | * [Syntactic Sugar](#syntactic-sugar) 28 | * [Control Flow](#control-flow) 29 | * [Semicolons](#semicolons) 30 | * [Language](#language) 31 | * [Smiley Face](#smiley-face) 32 | * [Credits](#credits) 33 | 34 | 35 | ## Naming 36 | 37 | 메소드 및 변수는 소문자로 시작한다. 38 | 메소드, 변수는 소문자로 시작해야 하지만, 모듈범위의 클래스명과 상수는 대문자로 한다. 39 | 40 | **추천:** 41 | 42 | ```swift 43 | let MaximumWidgetCount = 100 44 | 45 | class WidgetContainer { 46 | var widgetButton: UIButton 47 | let widgetHeightPercentage = 0.85 48 | } 49 | ``` 50 | 51 | **비추천:** 52 | 53 | ```swift 54 | let MAX_WIDGET_COUNT = 100 55 | 56 | class app_widgetContainer { 57 | var wBut: UIButton 58 | let wHeightPct = 0.85 59 | } 60 | ``` 61 | 62 | 믄맥이 정확하지 않는 경우, 함수 및 이니셜라이저에서는 전체로 이해할 수 있는 이름으로 구성된 매개변수가 좋습니다. 63 | 외부 매개변수명도 포함됩니다. 그것은 함수호출을 더 쉽게 이해할 수 있습니다. 64 | 65 | ```swift 66 | func dateFromString(dateString: NSString) -> NSDate 67 | func convertPointAt(#column: Int, #row: Int) -> CGPoint 68 | func timedAction(#delay: NSTimeInterval, perform action: SKAction) -> SKAction! 69 | 70 | // would be called like this: 71 | dateFromString("2014-03-14") 72 | convertPointAt(column: 42, row: 13) 73 | timedAction(delay: 1.0, perform: someOtherAction) 74 | ``` 75 | 76 | 메소드의 경우, 메소드명에 첫번째 매개변수의 참조를 포함하거나 표준 애플 기준에 따른다. 77 | 애플사 기준 78 | https://developer.apple.com/library/ios/documentation/swift/conceptual/swift_programming_language/Methods.html#//apple_ref/doc/uid/TP40014097-CH15-XID_356* 79 | 80 | ```swift 81 | class Guideline { 82 | func combineWithString(incoming: String, options: Dictionary?) { ... } 83 | func upvoteBy(amount: Int) { ... } 84 | } 85 | ``` 86 | 87 | 튜토리얼, 책, 댓글등의 함수를 참조시, 호출하는 쪽의 관점에서 필수 매개변수명을 포함하고 있어야 합니다. 88 | 문맥이 명확하고 정확한 이름이 중요하지 않는 경우, 메소드명만 사용할 수 있습니다. 89 | 90 | > Call `convertPointAt(column:row:)` from your own `init` implementation. 91 | > 92 | > If you implement `didSelectRowAtIndexPath`, remember to deselect the row when you're done. 93 | > 94 | > You shouldn't call the data source method `tableView(_:cellForRowAtIndexPath:)` directly. 95 | 96 | 97 | ### Class Prefixes 98 | 99 | Swift의 형은 모두 자동으로 모듈단위의 네임스페이스입니다. 100 | 따라서 이름때문에 충돌날 수 있는 것을 최소화하기 위해 프리픽스(접두사)는 필요하지 않습니다. 101 | 같은 이름으로 다른 모듈의 경우 모듈명과 모델명을 붙여서 명확하게 할 수 있습니다: 102 | 103 | 104 | ```swift 105 | import MyModule 106 | 107 | var myClass = MyModule.MyClass() 108 | ``` 109 | 110 | Swift의 형에는 프리픽스(접두사)를 사용하지 마십시오. 111 | 112 | Objective-C에서 사용하는 Swift를 공개하는 경우 알맞은 프리픽스를 제공할 수 있습니다. 113 | (아래 [Objective-C 스타일 가이드]처럼(https://github.com/raywenderlich/objective-c-style-guide)): 114 | 115 | ```swift 116 | @objc (RWTChicken) class Chicken { 117 | ... 118 | } 119 | ``` 120 | 121 | 122 | ## Spacing 123 | 124 | 탭보다 2칸의 공백 들여쓰기가 공백을 절약하고 줄바꿈은 하지 마십시오. 125 | Xcode에서 이 환경을 설정하세요. 126 | 메소드의 괄호 및 기타 괄호( `if`/` else`/ `switch`/` while`등), 127 | 항상 문장과 같은 줄에 오픈한 새로운 라인을 닫습니다. 128 |    129 | 130 | **추천:** 131 | ```swift 132 | if user.isHappy { 133 | //Do something 134 | } else { 135 | //Do something else 136 | } 137 | ``` 138 | 139 | **비추천:** 140 | ```swift 141 | if user.isHappy 142 | { 143 | //Do something 144 | } 145 | else { 146 | //Do something else 147 | } 148 | ``` 149 | 150 | 메소드 사이에 쉽게 확인할 수 있도록 하나의 빈줄이 있어야 합니다. 151 | 하나의 메소드에 공백구분이 너무 많은 경우 몇 가지 메소드로 분할하는 것이 좋습니다. 152 | 153 | ## Comments 154 | 155 | 주석을 필요로 하는 경우에는 코드의 특정 부분이 무엇인지를 설명하는 주석을 사용합니다. 156 | 주석관리를 통해 최신 상태로 유지해야 합니다. 157 | 158 | 코드는 가능한 문서로 있어야 하기에 인라인 블록 주석을 피하십시오. 159 | 예외: 문서를 생성하는데 사용하는 주석에는 적용되지 않습니다. 160 | 161 | 162 | ## Classes and Structures 163 | 164 | 좋은 클래스 정의의 예를 보여줍니다. 165 | 166 | ```swift 167 | class Circle: Shape { 168 | var x: Int, y: Int 169 | var radius: Double 170 | var diameter: Double { 171 | get { 172 | return radius * 2 173 | } 174 | set { 175 | radius = newValue / 2 176 | } 177 | } 178 | 179 | init(x: Int, y: Int, radius: Double) { 180 | self.x = x 181 | self.y = y 182 | self.radius = radius 183 | } 184 | 185 | convenience init(x: Int, y: Int, diameter: Double) { 186 | self.init(x: x, y: y, radius: diameter / 2) 187 | } 188 | 189 | func describe() -> String { 190 | return "I am a circle at \(centerString()) with an area of \(computeArea())" 191 | } 192 | 193 | override func computeArea() -> Double { 194 | return M_PI * radius * radius 195 | } 196 | 197 | private func centerString() -> String { 198 | return "(\(x),\(y))" 199 | } 200 | } 201 | ``` 202 | 203 | 위 예제는 다음 스타일 가이드를 제공하고 있습니다: 204 | 205 | 속성, 변수, 상수인수는 형을 지정하고 콜론 앞이 아닌 뒤에 공백을 넣습니다. 206 | 예: `x: Int`, `Circle: Shape` 207 | 공통의 목적/콘텍스트를 공유하는 경우 같은 행에 여러개의 변수와 스트럭쳐를 정의한다. 208 | getter/setter 정의 및 속성도 들여쓰기 합니다. 209 | 기본적으로 `internal`등의 한정자를 추가하지 마십시오. 210 | 메소드를 재정의하는 경우도 마찬가지로 액세스한정자를 반복하지 않습니다. 211 | 212 | ### Use of Self 213 | 214 | Swift는 개체의 속성 접근메소드 호출에서 `self`를 필요로 하지 않기 때문에 간결하게 하기 위해 `self` 사용을 피하십시오. 215 | 216 | 속성명과 인수의 초기화에서 구별을 위해 필요한 경우 폐쇄에서 속성을 참조하는 경우에는 명확하게 하기 위해 `self`를 사용하십시오. 217 | 218 | 219 | ```swift 220 | class BoardLocation { 221 | let row: Int, column: Int 222 | 223 | init(row: Int,column: Int) { 224 | self.row = row 225 | self.column = column 226 | 227 | let closure = { () -> () in 228 | println(self.row) 229 | } 230 | } 231 | } 232 | ``` 233 | 234 | ## Function Declarations 235 | 236 | 함수는 짧고 간결하게 여는 괄호를 포함하여 한줄로 요약합니다: 237 | 238 | ```swift 239 | func reticulateSplines(spline: [Double]) -> Bool { 240 | // reticulate code goes here 241 | } 242 | ``` 243 | 244 | 긴 이름의 함수는 알맞은 위치에서 줄바꿈을 하고 연속적인 행에 들여쓰기를 추가합니다: 245 | 246 | ```swift 247 | func reticulateSplines(spline: [Double], adjustmentFactor: Double, 248 | translateConstant: Int, comment: String) -> Bool { 249 | // reticulate code goes here 250 | } 251 | ``` 252 | 253 | 254 | ## Closures 255 | 256 | 가능한 TrailingClosures구문을 사용합시다. 모든 경우에 의미를 전달할 수 있는 설명적인 인수명을 사용합시다: 257 | TrailingClosures참고구문: http://qiita.com/edo_m18/items/1d93af7de75c6d415f19#2-6 258 | 259 | ```swift 260 | return SKAction.customActionWithDuration(effect.duration) { node, elapsedTime in 261 | // more code goes here 262 | } 263 | ``` 264 | 265 | 문맥이 명확한 단일형태의 closure는 암시적인 리턴을 사용합시다: 266 | 267 | ```swift 268 | attendeeList.sort { a, b in 269 | a > b 270 | } 271 | ``` 272 | 273 | 274 | ## Types 275 | 276 | 사용가능한 경우 반드시 Swift의 네이티브형을 사용합시다. 277 | 필요에 따라 완전한 세트를 사용할 수 있도록 Swift는. Objective-C를 브릿지해서 사용할 수 있습니다. 278 | 279 | **추천:** 280 | ```swift 281 | let width = 120.0 //Double 282 | let widthString = (width as NSNumber).stringValue //String 283 | ``` 284 | 285 | **비추천:** 286 | ```swift 287 | let width: NSNumber = 120.0 //NSNumber 288 | let widthString: NSString = width.stringValue //NSString 289 | ``` 290 | 291 | SpriteKit 코드로 변환을 피해서 코드가 더 간결해진다면 'CGFloat'를 사용합니다。 292 | 293 | ### Constants 294 | 295 | 상수는 `let`으로 정의합니다. 변수는 `var`로 정의합니다. 296 | `let`키워드를 사용하여 상수를 알맞게 정의하면 아마도 ‘var’보다 훨씬더 좋은 ‘let’을 사용하는 것입니다. 297 | 298 | **Tip:** *이 기준을 충족하는데 도움이 되는 기술로 모든 것을 상수로 정의한 컴파일러에 무리가 되는 것만 변수로 변경하는 것입니다. 299 | 300 | 301 | ### Optionals 302 | 303 | 값을 허용하는 곳에서는 변수와 함수의 리턴형식을 선택적 ‘?’으로 선언합시다. 304 | 나중에 사용하기 전에 초기화하는 것으 확실한 인스턴스 변수에만 Implicitly Unwrapped Optional형’!’으로 선언합시다. 305 | 예로 , viewDidLoad초기화하는 subview등이 있습니다. 306 | 307 | 선택적 값에 접근할 경우 한번 사용하고 있는 값이거나 체인에서 많은 선택사항이 있는경우. Optional chaining을 사용합시다: 308 | 309 | ```swift 310 | myOptional?.anotherOne?.optionalView?.setNeedsDisplay() 311 | ``` 312 | 313 | 1번 실행 및 여러번 실행을 수행하는데 적합한 경우는 optional binding을 사용합시다: 314 | 참고: http://qiita.com/cotrpepe/items/e30c7442733b93adf46a#3-optional-binding 315 | 316 | ```swift 317 | if let view = self.optionalView { 318 | // do many things with view 319 | } 320 | ``` 321 | 322 | ### Struct Initializers 323 | 324 | 레거시 CGGeometry 생성자보다 네이티브 Swift구조체 이니셜라이저를 사용합시다. 325 | 326 | **추천:** 327 | ```swift 328 | let bounds = CGRect(x: 40, y: 20, width: 120, height: 80) 329 | var centerPoint = CGPoint(x: 96, y: 42) 330 | ``` 331 | 332 | **비추천:** 333 | ```swift 334 | let bounds = CGRectMake(40, 20, 120, 80) 335 | var centerPoint = CGPointMake(96, 42) 336 | ``` 337 | 338 | ### Type Inference 339 | 340 | Swift 컴파일러는 변수와 상수 타입추론을 할 수 있습니다. 명시적인 형을 지정할 수 있지만 대부분의 경우 필요가 없습니다. 341 | 컴팩트한 코드에 컴파일러 상수 또는 변수 형 추론을 이용합시다. 342 | 343 | **추천:** 344 | ```swift 345 | let message = "Click the button" 346 | var currentBounds = computeViewBounds() 347 | ``` 348 | 349 | **비추천:** 350 | ```swift 351 | let message: String = "Click the button" 352 | var currentBounds: CGRect = computeViewBounds() 353 | ``` 354 | 355 | **NOTE** 이 지침을 준수하여 설명하려는 이름을 선택하는 것은 이전보다 더 중요하게 될 것입니다. 356 | 357 | ### Syntactic Sugar 358 | 359 | 제네릭 구문에서는 형 선언의 바로가기를 사용합시다. 360 | 361 | **추천:** 362 | ```swift 363 | var deviceModels: [String] 364 | var employees: [Int: String] 365 | var faxNumber: Int? 366 | ``` 367 | 368 | **비추천:** 369 | ```swift 370 | var deviceModels: Array 371 | var employees: Dictionary 372 | var faxNumber: Optional 373 | ``` 374 | 375 | 376 | 377 | ## Control Flow 378 | 379 | `for` loop over the `for-condition-increment`보다,`for-in`을 사용합시다. 380 | 381 | **추천:** 382 | ```swift 383 | for _ in 0..<3 { 384 | println("Hello three times") 385 | } 386 | 387 | for person in attendeeList { 388 | // do something 389 | } 390 | ``` 391 | 392 | **비추천:** 393 | ```swift 394 | for var i = 0; i < 3; i++ { 395 | println("Hello three times") 396 | } 397 | 398 | for var i = 0; i < attendeeList.count; i++ { 399 | let person = attendeeList[i] 400 | // do something 401 | } 402 | ``` 403 | 404 | 405 | ## Semicolons 406 | 407 | 코드의 각 문장뒤에 세미콜론이 필요하지 않습니다. 한줄에 여러 문장을 결합하는 경우에만 필요합니다. 408 | 409 | 세미콜론을 사용하여 여러 줄을 한줄로 사용하지 마십시오. 410 | 411 | 이 규칙의 유일한 예외는 ‘for-conditional-increment’입니다. 그러나 가능한 ‘for-in’을 사용합니다. 412 | 413 | **추천:** 414 | ```swift 415 | var swift = "not a scripting language" 416 | ``` 417 | 418 | **비추천:** 419 | ```swift 420 | var swift = "not a scripting language"; 421 | ``` 422 | 423 | **NOTE**: Swift는 세미콜론을 생략해도 되는 JavaScript와는 상당히 다릅니다. 세미콜론을 생략하는 것이 일반적으로는 안전하지 않다고 이야기합니다.(http://stackoverflow.com/questions/444080/do-you-recommend-using-semicolons-after-every-statement-in-javascript) 424 | 425 | 426 | 427 | ## Language 428 | 429 | Apple의 API와 일치시키기 위해 미국식 영어찰자를 사용하십시오. 430 | 431 | **추천:** 432 | ```swift 433 | var color = "red" 434 | ``` 435 | 436 | **비추천:** 437 | ```swift 438 | var colour = "red" 439 | ``` 440 | 441 | ## Smiley Face 442 | 443 | 웃는얼굴이 raywenderlich.com사이트의 놀라운 스타일을 보여준다. 웃는 행복과 흥분을 가져다주는 미소임을 코딩주제로 매우 중요합니다. 닫힌 대괄호는 ‘]’을 사용합니다. 444 | 왜냐하면 ASCII아트를 사용하여 캡쳐할 수 있는 최대 미소를 나타낼 수 있기 때문입니다. 괄호는 ‘)’는 어중간한 미솔로 작성하기 때문에 바람직하지 않습니다. 445 | 446 | **추천:** 447 | ``` 448 | :] 449 | ``` 450 | 451 | **비추천:** 452 | ``` 453 | :) 454 | ``` 455 | 456 | 457 | ## Credits 458 | 459 | This style guide is a collaborative effort from the most stylish raywenderlich.com team members: 460 | 461 | * [Soheil Moayedi Azarpour](https://github.com/moayes) 462 | * [Scott Berrevoets](https://github.com/Scott90) 463 | * [Eric Cerney](https://github.com/ecerney) 464 | * [Sam Davies](https://github.com/sammyd) 465 | * [Evan Dekhayser](https://github.com/edekhayser) 466 | * [Jean-Pierre Distler](https://github.com/pdistler) 467 | * [Colin Eberhardt](https://github.com/ColinEberhardt) 468 | * [Greg Heo](https://github.com/gregheo) 469 | * [Matthijs Hollemans](https://github.com/hollance) 470 | * [Erik Kerber](https://github.com/eskerber) 471 | * [Christopher LaPollo](https://github.com/elephantronic) 472 | * [Andy Pereira](https://github.com/macandyp) 473 | * [Ryan Nystrom](https://github.com/rnystrom) 474 | * [Cesare Rocchi](https://github.com/funkyboy) 475 | * [Ellen Shapiro](https://github.com/designatednerd) 476 | * [Marin Todorov](https://github.com/icanzilb) 477 | * [Chris Wagner](https://github.com/cwagdev) 478 | * [Ray Wenderlich](https://github.com/rwenderlich) 479 | * [Jack Wu](https://github.com/jackwu95) 480 | 481 | Hat tip to [Nicholas Waynik](https://github.com/ndubbs) and the [Objective-C Style Guide](https://github.com/raywenderlich/objective-c-style-guide) team! 482 | 483 | We also drew inspiration from Apple’s reference material on Swift: 484 | 485 | * [The Swift Programming Language](https://developer.apple.com/library/prerelease/ios/documentation/swift/conceptual/swift_programming_language/index.html) 486 | * [Using Swift with Cocoa and Objective-C](https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/BuildingCocoaApps/index.html) 487 | * [Swift Standard Library Reference](https://developer.apple.com/library/prerelease/ios/documentation/General/Reference/SwiftStandardLibraryReference/index.html) 488 | 489 | -------------------------------------------------------------------------------- /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 conciseness, readability, and simplicity. 6 | 7 | Writing Objective-C? Check out our [Objective-C Style Guide](https://github.com/raywenderlich/objective-c-style-guide) too. 8 | 9 | ## Table of Contents 10 | 11 | * [Correctness](#correctness) 12 | * [Naming](#naming) 13 | * [Protocols](#protocols) 14 | * [Enumerations](#enumerations) 15 | * [Prose](#prose) 16 | * [Selectors](#selectors) 17 | * [Generics](#generics) 18 | * [Class Prefixes](#class-prefixes) 19 | * [Language](#language) 20 | * [Code Organization](#code-organization) 21 | * [Protocol Conformance](#protocol-conformance) 22 | * [Unused Code](#unused-code) 23 | * [Minimal Imports](#minimal-imports) 24 | * [Spacing](#spacing) 25 | * [Comments](#comments) 26 | * [Classes and Structures](#classes-and-structures) 27 | * [Use of Self](#use-of-self) 28 | * [Protocol Conformance](#protocol-conformance) 29 | * [Computed Properties](#computed-properties) 30 | * [Final](#final) 31 | * [Function Declarations](#function-declarations) 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 | * [Struct Initializers](#struct-initializers) 38 | * [Lazy Initialization](#lazy-initialization) 39 | * [Type Inference](#type-inference) 40 | * [Syntactic Sugar](#syntactic-sugar) 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 | * [Golden Path](#golden-path) 47 | * [Failing Guards](#failing-guards) 48 | * [Semicolons](#semicolons) 49 | * [Parentheses](#parentheses) 50 | * [Copyright Statement](#copyright-statement) 51 | * [Smiley Face](#smiley-face) 52 | * [Credits](#credits) 53 | 54 | 55 | ## Correctness 56 | 57 | Consider warnings to be errors. This rule informs many stylistic decisions such as not to use the `++` or `--` operators, C-style for loops, or strings as selectors. 58 | 59 | ## Naming 60 | 61 | 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. 62 | 63 | **Preferred:** 64 | 65 | ```swift 66 | private let maximumWidgetCount = 100 67 | 68 | class WidgetContainer { 69 | var widgetButton: UIButton 70 | let widgetHeightPercentage = 0.85 71 | } 72 | ``` 73 | 74 | **Not Preferred:** 75 | 76 | ```swift 77 | let MAX_WIDGET_COUNT = 100 78 | 79 | class app_widgetContainer { 80 | var wBut: UIButton 81 | let wHeightPct = 0.85 82 | } 83 | ``` 84 | 85 | Abbreviations and acronyms should generally be avoided. Following the [API Design Guidelines](https://swift.org/documentation/api-design-guidelines/#follow-case-conventions), abbreviations and initialisms that appear in all uppercase should be uniformly uppercase or lowercase. Examples: 86 | 87 | **Preferred** 88 | ```swift 89 | let urlString: URLString 90 | let userID: UserID 91 | ``` 92 | 93 | **Not Preferred** 94 | ```swift 95 | let uRLString: UrlString 96 | let userId: UserId 97 | ``` 98 | 99 | For functions and init methods, prefer named parameters for all arguments unless the context is very clear. Include external parameter names if it makes function calls more readable. 100 | 101 | ```swift 102 | func dateFromString(dateString: String) -> NSDate 103 | func convertPointAt(column column: Int, row: Int) -> CGPoint 104 | func timedAction(afterDelay delay: NSTimeInterval, perform action: SKAction) -> SKAction! 105 | 106 | // would be called like this: 107 | dateFromString("2014-03-14") 108 | convertPointAt(column: 42, row: 13) 109 | timedAction(afterDelay: 1.0, perform: someOtherAction) 110 | ``` 111 | 112 | For methods, follow the standard Apple convention of referring to the first parameter in the method name: 113 | 114 | ```swift 115 | class Counter { 116 | func combineWith(otherCounter: Counter, options: Dictionary?) { ... } 117 | func incrementBy(amount: Int) { ... } 118 | } 119 | ``` 120 | 121 | ### Protocols 122 | 123 | Following Apple's API Design Guidelines, protocols names that describe what something is should be a noun. Examples: `Collection`, `WidgetFactory`. Protocols names that describe an ability should end in -ing, -able, or -ible. Examples: `Equatable`, `Resizing`. 124 | 125 | ### Enumerations 126 | 127 | Following Apple's API Design Guidelines for Swift 3, use lowerCamelCase for enumeration values. 128 | 129 | ```swift 130 | enum Shape { 131 | case rectangle 132 | case square 133 | case rightTriangle 134 | case equilateralTriangle 135 | } 136 | ``` 137 | 138 | ### Prose 139 | 140 | When referring to functions in prose (tutorials, books, comments) include the required parameter names from the caller's perspective or `_` for unnamed parameters. Examples: 141 | 142 | > Call `convertPointAt(column:row:)` from your own `init` implementation. 143 | > 144 | > If you call `dateFromString(_:)` make sure that you provide a string with the format "yyyy-MM-dd". 145 | > 146 | > If you call `timedAction(afterDelay:perform:)` from `viewDidLoad()` remember to provide an adjusted delay value and an action to perform. 147 | > 148 | > You shouldn't call the data source method `tableView(_:cellForRowAtIndexPath:)` directly. 149 | 150 | 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. 151 | 152 | ![Methods in Xcode jump bar](screens/xcode-jump-bar.png) 153 | 154 | 155 | ### Class Prefixes 156 | 157 | 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. 158 | 159 | ```swift 160 | import SomeModule 161 | 162 | let myClass = MyModule.UsefulClass() 163 | ``` 164 | 165 | ### Selectors 166 | 167 | 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. 168 | 169 | **Preferred:** 170 | ```swift 171 | let sel = #selector(viewDidLoad) 172 | ``` 173 | 174 | **Not Preferred:** 175 | ```swift 176 | let sel = #selector(ViewController.viewDidLoad) 177 | ``` 178 | 179 | ### Generics 180 | 181 | 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`. 182 | 183 | **Preferred:** 184 | ```swift 185 | struct Stack { ... } 186 | func writeTo(inout target: Target) 187 | func max(x: T, _ y: T) -> T 188 | ``` 189 | 190 | **Not Preferred:** 191 | ```swift 192 | struct Stack { ... } 193 | func writeTo(inout t: target) 194 | func max(x: Thing, _ y: Thing) -> Thing 195 | ``` 196 | 197 | ### Language 198 | 199 | Use US English spelling to match Apple's API. 200 | 201 | **Preferred:** 202 | ```swift 203 | let color = "red" 204 | ``` 205 | 206 | **Not Preferred:** 207 | ```swift 208 | let colour = "red" 209 | ``` 210 | 211 | ## Code Organization 212 | 213 | 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. 214 | 215 | ### Protocol Conformance 216 | 217 | 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. 218 | 219 | **Preferred:** 220 | ```swift 221 | class MyViewcontroller: UIViewController { 222 | // class stuff here 223 | } 224 | 225 | // MARK: - UITableViewDataSource 226 | extension MyViewcontroller: UITableViewDataSource { 227 | // table view data source methods 228 | } 229 | 230 | // MARK: - UIScrollViewDelegate 231 | extension MyViewcontroller: UIScrollViewDelegate { 232 | // scroll view delegate methods 233 | } 234 | ``` 235 | 236 | **Not Preferred:** 237 | ```swift 238 | class MyViewcontroller: UIViewController, UITableViewDataSource, UIScrollViewDelegate { 239 | // all methods 240 | } 241 | ``` 242 | 243 | 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 overriden. When to preserve the extension groups is left to the discretion of the author. 244 | 245 | For UIKit view controllers, consider grouping lifecycle, custom accessors, and IBAction in separate class extensions. 246 | 247 | ### Unused Code 248 | 249 | 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. 250 | 251 | Aspirational methods not directly associated with the tutorial whose implementation simply calls the super class should also be removed. This includes any empty/unused UIApplicationDelegate methods. 252 | 253 | **Not Preferred:** 254 | ```swift 255 | override func didReceiveMemoryWarning() { 256 | super.didReceiveMemoryWarning() 257 | // Dispose of any resources that can be recreated. 258 | } 259 | 260 | override func numberOfSectionsInTableView(tableView: UITableView) -> Int { 261 | // #warning Incomplete implementation, return the number of sections 262 | return 1 263 | } 264 | 265 | override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 266 | // #warning Incomplete implementation, return the number of rows 267 | return Database.contacts.count 268 | } 269 | 270 | ``` 271 | 272 | **Preferred:** 273 | ```swift 274 | override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 275 | return Database.contacts.count 276 | } 277 | ``` 278 | ### Minimal Imports 279 | 280 | Keep imports minimal. For example, don't import `UIKit` when importing `Foundation` will suffice. 281 | 282 | ## Spacing 283 | 284 | * 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: 285 | 286 | ![Xcode indent settings](screens/indentation.png) 287 | 288 | ![Xcode Project settings](screens/project_settings.png) 289 | 290 | * 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. 291 | * Tip: You can re-indent by selecting some code (or ⌘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. 292 | 293 | **Preferred:** 294 | ```swift 295 | if user.isHappy { 296 | // Do something 297 | } else { 298 | // Do something else 299 | } 300 | ``` 301 | 302 | **Not Preferred:** 303 | ```swift 304 | if user.isHappy 305 | { 306 | // Do something 307 | } 308 | else { 309 | // Do something else 310 | } 311 | ``` 312 | 313 | * There should be exactly one blank line between methods 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. 314 | 315 | * Colons always have no space on the left and one space on the right. Exceptions are the ternary operator `? :` and empty dictionary `[:]`. 316 | 317 | **Preferred:** 318 | ```swift 319 | class TestDatabase: Database { 320 | var data: [String: CGFloat] = ["A": 1.2, "B": 3.2] 321 | } 322 | ``` 323 | 324 | **Not Preferred:** 325 | ```swift 326 | class TestDatabase : Database { 327 | var data :[String:CGFloat] = ["A" : 1.2, "B":3.2] 328 | } 329 | ``` 330 | 331 | ## Comments 332 | 333 | 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. 334 | 335 | 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.* 336 | 337 | 338 | ## Classes and Structures 339 | 340 | ### Which one to use? 341 | 342 | 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. 343 | 344 | 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. 345 | 346 | 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. 347 | 348 | ### Example definition 349 | 350 | Here's an example of a well-styled class definition: 351 | 352 | ```swift 353 | class Circle: Shape { 354 | var x: Int, y: Int 355 | var radius: Double 356 | var diameter: Double { 357 | get { 358 | return radius * 2 359 | } 360 | set { 361 | radius = newValue / 2 362 | } 363 | } 364 | 365 | init(x: Int, y: Int, radius: Double) { 366 | self.x = x 367 | self.y = y 368 | self.radius = radius 369 | } 370 | 371 | convenience init(x: Int, y: Int, diameter: Double) { 372 | self.init(x: x, y: y, radius: diameter / 2) 373 | } 374 | 375 | func describe() -> String { 376 | return "I am a circle at \(centerString()) with an area of \(computeArea())" 377 | } 378 | 379 | override func computeArea() -> Double { 380 | return M_PI * radius * radius 381 | } 382 | 383 | private func centerString() -> String { 384 | return "(\(x),\(y))" 385 | } 386 | } 387 | ``` 388 | 389 | The example above demonstrates the following style guidelines: 390 | 391 | + 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`. 392 | + Define multiple variables and structures on a single line if they share a common purpose / context. 393 | + Indent getter and setter definitions and property observers. 394 | + Don't add modifiers such as `internal` when they're already the default. Similarly, don't repeat the access modifier when overriding a method. 395 | 396 | 397 | ### Use of Self 398 | 399 | For conciseness, avoid using `self` since Swift does not require it to access an object's properties or invoke its methods. 400 | 401 | 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): 402 | 403 | ```swift 404 | class BoardLocation { 405 | let row: Int, column: Int 406 | 407 | init(row: Int, column: Int) { 408 | self.row = row 409 | self.column = column 410 | 411 | let closure = { 412 | print(self.row) 413 | } 414 | } 415 | } 416 | ``` 417 | 418 | ### Computed Properties 419 | 420 | 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. 421 | 422 | **Preferred:** 423 | ```swift 424 | var diameter: Double { 425 | return radius * 2 426 | } 427 | ``` 428 | 429 | **Not Preferred:** 430 | ```swift 431 | var diameter: Double { 432 | get { 433 | return radius * 2 434 | } 435 | } 436 | ``` 437 | 438 | ### Final 439 | 440 | Mark classes `final` when inheritance is not intended. Example: 441 | 442 | ```swift 443 | // Turn any generic type into a reference type using this Box class. 444 | final class Box { 445 | let value: T 446 | init(_ value: T) { 447 | self.value = value 448 | } 449 | } 450 | ``` 451 | 452 | ## Function Declarations 453 | 454 | Keep short function declarations on one line including the opening brace: 455 | 456 | ```swift 457 | func reticulateSplines(spline: [Double]) -> Bool { 458 | // reticulate code goes here 459 | } 460 | ``` 461 | 462 | For functions with long signatures, add line breaks at appropriate points and add an extra indent on subsequent lines: 463 | 464 | ```swift 465 | func reticulateSplines(spline: [Double], adjustmentFactor: Double, 466 | translateConstant: Int, comment: String) -> Bool { 467 | // reticulate code goes here 468 | } 469 | ``` 470 | 471 | ## Closure Expressions 472 | 473 | 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. 474 | 475 | **Preferred:** 476 | ```swift 477 | UIView.animateWithDuration(1.0) { 478 | self.myView.alpha = 0 479 | } 480 | 481 | UIView.animateWithDuration(1.0, 482 | animations: { 483 | self.myView.alpha = 0 484 | }, 485 | completion: { finished in 486 | self.myView.removeFromSuperview() 487 | } 488 | ) 489 | ``` 490 | 491 | **Not Preferred:** 492 | ```swift 493 | UIView.animateWithDuration(1.0, animations: { 494 | self.myView.alpha = 0 495 | }) 496 | 497 | UIView.animateWithDuration(1.0, 498 | animations: { 499 | self.myView.alpha = 0 500 | }) { f in 501 | self.myView.removeFromSuperview() 502 | } 503 | ``` 504 | 505 | For single-expression closures where the context is clear, use implicit returns: 506 | 507 | ```swift 508 | attendeeList.sort { a, b in 509 | a > b 510 | } 511 | ``` 512 | 513 | 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: 514 | 515 | ```swift 516 | let value = numbers.map { $0 * 2 }.filter { $0 % 3 == 0 }.indexOf(90) 517 | 518 | let value = numbers 519 | .map {$0 * 2} 520 | .filter {$0 > 50} 521 | .map {$0 + 10} 522 | ``` 523 | 524 | ## Types 525 | 526 | Always use Swift's native types when available. Swift offers bridging to Objective-C so you can still use the full set of methods as needed. 527 | 528 | **Preferred:** 529 | ```swift 530 | let width = 120.0 // Double 531 | let widthString = (width as NSNumber).stringValue // String 532 | ``` 533 | 534 | **Not Preferred:** 535 | ```swift 536 | let width: NSNumber = 120.0 // NSNumber 537 | let widthString: NSString = width.stringValue // NSString 538 | ``` 539 | 540 | In Sprite Kit code, use `CGFloat` if it makes the code more succinct by avoiding too many conversions. 541 | 542 | ### Constants 543 | 544 | 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. 545 | 546 | **Tip:** A good technique is to define everything using `let` and only change it to `var` if the compiler complains! 547 | 548 | You can define constants on a type rather than 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: 549 | 550 | **Preferred:** 551 | ```swift 552 | enum Math { 553 | static let e = 2.718281828459045235360287 554 | static let pi = 3.141592653589793238462643 555 | } 556 | 557 | radius * Math.pi * 2 // circumference 558 | 559 | ``` 560 | **Note:** The advantage of using a case-less enumeration is that it can't accidentally be instantiated and works as a pure namespace. 561 | 562 | **Not Preferred:** 563 | ```swift 564 | let e = 2.718281828459045235360287 // pollutes global namespace 565 | let pi = 3.141592653589793238462643 566 | 567 | radius * pi * 2 // is pi instance data or a global constant? 568 | ``` 569 | 570 | ### Static Methods and Variable Type Properties 571 | 572 | 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. 573 | 574 | ### Optionals 575 | 576 | Declare variables and function return types as optional with `?` where a nil value is acceptable. 577 | 578 | 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`. 579 | 580 | When accessing an optional value, use optional chaining if the value is only accessed once or if there are many optionals in the chain: 581 | 582 | ```swift 583 | self.textContainer?.textLabel?.setNeedsDisplay() 584 | ``` 585 | 586 | Use optional binding when it's more convenient to unwrap once and perform multiple operations: 587 | 588 | ```swift 589 | if let textContainer = self.textContainer { 590 | // do many things with textContainer 591 | } 592 | ``` 593 | 594 | When naming optional variables and properties, avoid naming them like `optionalString` or `maybeView` since their optional-ness is already in the type declaration. 595 | 596 | For optional binding, shadow the original name when appropriate rather than using names like `unwrappedView` or `actualLabel`. 597 | 598 | **Preferred:** 599 | ```swift 600 | var subview: UIView? 601 | var volume: Double? 602 | 603 | // later on... 604 | if let subview = subview, volume = volume { 605 | // do something with unwrapped subview and volume 606 | } 607 | ``` 608 | 609 | **Not Preferred:** 610 | ```swift 611 | var optionalSubview: UIView? 612 | var volume: Double? 613 | 614 | if let unwrappedSubview = optionalSubview { 615 | if let realVolume = volume { 616 | // do something with unwrappedSubview and realVolume 617 | } 618 | } 619 | ``` 620 | 621 | ### Struct Initializers 622 | 623 | Use the native Swift struct initializers rather than the legacy CGGeometry constructors. 624 | 625 | **Preferred:** 626 | ```swift 627 | let bounds = CGRect(x: 40, y: 20, width: 120, height: 80) 628 | let centerPoint = CGPoint(x: 96, y: 42) 629 | ``` 630 | 631 | **Not Preferred:** 632 | ```swift 633 | let bounds = CGRectMake(40, 20, 120, 80) 634 | let centerPoint = CGPointMake(96, 42) 635 | ``` 636 | 637 | Prefer the struct-scope constants `CGRect.infinite`, `CGRect.null`, etc. over global constants `CGRectInfinite`, `CGRectNull`, etc. For existing variables, you can use the shorter `.zero`. 638 | 639 | 640 | ### Lazy Initialization 641 | 642 | Consider using lazy initialization for finer grain 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: 643 | 644 | ```swift 645 | lazy var locationManager: CLLocationManager = self.makeLocationManager() 646 | 647 | private func makeLocationManager() -> CLLocationManager { 648 | let manager = CLLocationManager() 649 | manager.desiredAccuracy = kCLLocationAccuracyBest 650 | manager.delegate = self 651 | manager.requestAlwaysAuthorization() 652 | return manager 653 | } 654 | ``` 655 | 656 | **Notes:** 657 | - `[unowned self]` is not required here. A retain cycle is not created. 658 | - Location manager has a side-effect for popping up UI to ask the user for permission so fine grain control makes sense here. 659 | 660 | 661 | ### Type Inference 662 | 663 | 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`. 664 | 665 | **Preferred:** 666 | ```swift 667 | let message = "Click the button" 668 | let currentBounds = computeViewBounds() 669 | var names = ["Mic", "Sam", "Christine"] 670 | let maximumWidth: CGFloat = 106.5 671 | ``` 672 | 673 | **Not Preferred:** 674 | ```swift 675 | let message: String = "Click the button" 676 | let currentBounds: CGRect = computeViewBounds() 677 | let names = [String]() 678 | ``` 679 | 680 | #### Type Annotation for Empty Arrays and Dictionaries 681 | 682 | For empty arrays and dictionaries, use type annotation. (For an array or dictionary assigned to a large, multi-line literal, use type annotation.) 683 | 684 | **Preferred:** 685 | ```swift 686 | var names: [String] = [] 687 | var lookup: [String: Int] = [:] 688 | ``` 689 | 690 | **Not Preferred:** 691 | ```swift 692 | var names = [String]() 693 | var lookup = [String: Int]() 694 | ``` 695 | 696 | **NOTE**: Following this guideline means picking descriptive names is even more important than before. 697 | 698 | 699 | ### Syntactic Sugar 700 | 701 | Prefer the shortcut versions of type declarations over the full generics syntax. 702 | 703 | **Preferred:** 704 | ```swift 705 | var deviceModels: [String] 706 | var employees: [Int: String] 707 | var faxNumber: Int? 708 | ``` 709 | 710 | **Not Preferred:** 711 | ```swift 712 | var deviceModels: Array 713 | var employees: Dictionary 714 | var faxNumber: Optional 715 | ``` 716 | 717 | ## Functions vs Methods 718 | 719 | 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. 720 | 721 | Free functions are most appropriate when they aren't associated with any particular type or instance. 722 | 723 | **Preferred** 724 | ```swift 725 | let sorted = items.mergeSort() // easily discoverable 726 | rocket.launch() // clearly acts on the model 727 | ``` 728 | 729 | **Not Preferred** 730 | ```swift 731 | let sorted = mergeSort(items) // hard to discover 732 | launch(&rocket) 733 | ``` 734 | 735 | **Free Function Exceptions** 736 | ```swift 737 | let tuples = zip(a, b) // feels natural as a free function (symmetry) 738 | let value = max(x,y,z) // another free function that feels natural 739 | ``` 740 | 741 | ## Memory Management 742 | 743 | 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. 744 | 745 | ### Extending object lifetime 746 | 747 | Extend object lifetime using the `[weak self]` and `guard let strongSelf = 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 unwrapping. 748 | 749 | **Preferred** 750 | ```swift 751 | resource.request().onComplete { [weak self] response in 752 | guard let strongSelf = self else { return } 753 | let model = strongSelf.updateModel(response) 754 | strongSelf.updateUI(model) 755 | } 756 | ``` 757 | 758 | **Not Preferred** 759 | ```swift 760 | // might crash if self is released before response returns 761 | resource.request().onComplete { [unowned self] response in 762 | let model = self.updateModel(response) 763 | self.updateUI(model) 764 | } 765 | ``` 766 | 767 | **Not Preferred** 768 | ```swift 769 | // deallocate could happen between updating the model and updating UI 770 | resource.request().onComplete { [weak self] response in 771 | let model = self?.updateModel(response) 772 | self?.updateUI(model) 773 | } 774 | ``` 775 | 776 | ## Access Control 777 | 778 | 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`. 779 | 780 | **Preferred:** 781 | ```swift 782 | class TimeMachine { 783 | private dynamic lazy var fluxCapacitor = FluxCapacitor() 784 | } 785 | ``` 786 | 787 | **Not Preferred:** 788 | ```swift 789 | class TimeMachine { 790 | lazy dynamic private var fluxCapacitor = FluxCapacitor() 791 | } 792 | ``` 793 | 794 | ## Control Flow 795 | 796 | Prefer the `for-in` style of `for` loop over the `while-condition-increment` style. 797 | 798 | **Preferred:** 799 | ```swift 800 | for _ in 0..<3 { 801 | print("Hello three times") 802 | } 803 | 804 | for (index, person) in attendeeList.enumerate() { 805 | print("\(person) is at position #\(index)") 806 | } 807 | 808 | for index in 0.stride(to: items.count, by: 2) { 809 | print(index) 810 | } 811 | 812 | for index in (0...3).reverse() { 813 | print(index) 814 | } 815 | ``` 816 | 817 | **Not Preferred:** 818 | ```swift 819 | var i = 0 820 | while i < 3 { 821 | print("Hello three times") 822 | i += 1 823 | } 824 | 825 | 826 | var i = 0 827 | while i < attendeeList.count { 828 | let person = attendeeList[i] 829 | print("\(person) is at position #\(i)") 830 | i += 1 831 | } 832 | ``` 833 | ## Golden Path 834 | 835 | 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. 836 | 837 | **Preferred:** 838 | ```swift 839 | func computeFFT(context: Context?, inputData: InputData?) throws -> Frequencies { 840 | 841 | guard let context = context else { throw FFTError.noContext } 842 | guard let inputData = inputData else { throw FFTError.noInputData } 843 | 844 | // use context and input to compute the frequencies 845 | 846 | return frequencies 847 | } 848 | ``` 849 | 850 | **Not Preferred:** 851 | ```swift 852 | func computeFFT(context: Context?, inputData: InputData?) throws -> Frequencies { 853 | 854 | if let context = context { 855 | if let inputData = inputData { 856 | // use context and input to compute the frequencies 857 | 858 | return frequencies 859 | } 860 | else { 861 | throw FFTError.noInputData 862 | } 863 | } 864 | else { 865 | throw FFTError.noContext 866 | } 867 | } 868 | ``` 869 | 870 | When multiple optionals are unwrapped either with `guard` or `if let`, minimize nesting by using the compound version when possible. Example: 871 | 872 | **Preferred:** 873 | ```swift 874 | guard let number1 = number1, number2 = number2, number3 = number3 else { fatalError("impossible") } 875 | // do something with numbers 876 | ``` 877 | 878 | **Not Preferred:** 879 | ```swift 880 | if let number1 = number1 { 881 | if let number2 = number2 { 882 | if let number3 = number3 { 883 | // do something with numbers 884 | } 885 | else { 886 | fatalError("impossible") 887 | } 888 | } 889 | else { 890 | fatalError("impossible") 891 | } 892 | } 893 | else { 894 | fatalError("impossible") 895 | } 896 | ``` 897 | 898 | ### Failing Guards 899 | 900 | 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. 901 | 902 | ## Semicolons 903 | 904 | 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. 905 | 906 | Do not write multiple statements on a single line separated with semicolons. 907 | 908 | 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. 909 | 910 | **Preferred:** 911 | ```swift 912 | let swift = "not a scripting language" 913 | ``` 914 | 915 | **Not Preferred:** 916 | ```swift 917 | let swift = "not a scripting language"; 918 | ``` 919 | 920 | **NOTE**: Swift is very different from JavaScript, where omitting semicolons is [generally considered unsafe](http://stackoverflow.com/questions/444080/do-you-recommend-using-semicolons-after-every-statement-in-javascript) 921 | 922 | ## Parentheses 923 | 924 | Parentheses around conditionals are not required and should be omitted. 925 | 926 | **Preferred:** 927 | ```swift 928 | if name == "Hello" { 929 | print("World") 930 | } 931 | ``` 932 | 933 | **Not Preferred:** 934 | ```swift 935 | if (name == "Hello") { 936 | print("World") 937 | } 938 | ``` 939 | 940 | ## Copyright Statement 941 | 942 | The following copyright statement should be included at the top of every source 943 | file: 944 | 945 | /** 946 | * Copyright (c) 2016 Razeware LLC 947 | * 948 | * Permission is hereby granted, free of charge, to any person obtaining a copy 949 | * of this software and associated documentation files (the "Software"), to deal 950 | * in the Software without restriction, including without limitation the rights 951 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 952 | * copies of the Software, and to permit persons to whom the Software is 953 | * furnished to do so, subject to the following conditions: 954 | * 955 | * The above copyright notice and this permission notice shall be included in 956 | * all copies or substantial portions of the Software. 957 | * 958 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 959 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 960 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 961 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 962 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 963 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 964 | * THE SOFTWARE. 965 | */ 966 | 967 | ## Smiley Face 968 | 969 | Smiley faces are a very prominent style feature of the raywenderlich.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. 970 | 971 | **Preferred:** 972 | ``` 973 | :] 974 | ``` 975 | 976 | **Not Preferred:** 977 | ``` 978 | :) 979 | ``` 980 | 981 | ## Credits 982 | 983 | [Ray Fix](https://github.com/rayfix) currently maintains this style guide. 984 | It is a collaborative effort from the most stylish raywenderlich.com team members and its community: 985 | 986 | * [Jawwad Ahmad](https://github.com/jawwad) 987 | * [Soheil Moayedi Azarpour](https://github.com/moayes) 988 | * [Scott Berrevoets](https://github.com/Scott90) 989 | * [Eric Cerney](https://github.com/ecerney) 990 | * [Sam Davies](https://github.com/sammyd) 991 | * [Evan Dekhayser](https://github.com/edekhayser) 992 | * [Jean-Pierre Distler](https://github.com/pdistler) 993 | * [Colin Eberhardt](https://github.com/ColinEberhardt) 994 | * [Ray Fix](https://github.com/rayfix) 995 | * [Joshua Greene](https://github.com/JRG-Developer) 996 | * [Greg Heo](https://github.com/gregheo) 997 | * [Matthijs Hollemans](https://github.com/hollance) 998 | * [Erik Kerber](https://github.com/eskerber) 999 | * [Christopher LaPollo](https://github.com/elephantronic) 1000 | * [Ben Morrow](https://github.com/benmorrow) 1001 | * [Andy Pereira](https://github.com/macandyp) 1002 | * [Ryan Nystrom](https://github.com/rnystrom) 1003 | * [Andy Obusek](https://github.com/obuseme) 1004 | * [Cesare Rocchi](https://github.com/funkyboy) 1005 | * [Ellen Shapiro](https://github.com/designatednerd) 1006 | * [Marin Todorov](https://github.com/icanzilb) 1007 | * [Chris Wagner](https://github.com/cwagdev) 1008 | * [Ray Wenderlich](https://github.com/rwenderlich) 1009 | * [Jack Wu](https://github.com/jackwu95) 1010 | 1011 | Hat tip to [Nicholas Waynik](https://github.com/ndubbs) and the [Objective-C Style Guide](https://github.com/raywenderlich/objective-c-style-guide) team! 1012 | 1013 | We also draw inspiration from Apple’s reference material on Swift: 1014 | 1015 | * [The Swift API Design Guidelines](https://swift.org/documentation/api-design-guidelines/) 1016 | * [The Swift Programming Language](https://developer.apple.com/library/prerelease/ios/documentation/swift/conceptual/swift_programming_language/index.html) 1017 | * [Using Swift with Cocoa and Objective-C](https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/BuildingCocoaApps/index.html) 1018 | * [Swift Standard Library Reference](https://developer.apple.com/library/prerelease/ios/documentation/General/Reference/SwiftStandardLibraryReference/index.html) 1019 | --------------------------------------------------------------------------------