├── LICENSE ├── README.md └── SwiftTips.playground ├── Pages ├── 01 - Using map on optional values.xcplaygroundpage │ └── Contents.swift ├── 02 - Generating all cases for an Enum.xcplaygroundpage │ └── Contents.swift ├── 03 - Encapsulating state within a function.xcplaygroundpage │ └── Contents.swift ├── 04 - Typealiases for functions.xcplaygroundpage │ └── Contents.swift ├── 05 - Defining operators on function types.xcplaygroundpage │ └── Contents.swift ├── 06 - Storing functions rather than values.xcplaygroundpage │ └── Contents.swift ├── 07 - Implementing the builder pattern with keypaths.xcplaygroundpage │ └── Contents.swift ├── 08 - Achieving systematic validation of data.xcplaygroundpage │ └── Contents.swift ├── 09 - Implicit initialization from literal values.xcplaygroundpage │ └── Contents.swift ├── 10 - Observing new and old value with RxSwift.xcplaygroundpage │ └── Contents.swift ├── 11 - Using @autoclosure for cleaner call sites.xcplaygroundpage │ └── Contents.swift ├── 12 - Easily generating arrays of data.xcplaygroundpage │ └── Contents.swift ├── 13 - Simplifying complex conditions with pattern matching.xcplaygroundpage │ └── Contents.swift ├── 14 - Manufacturing cache-efficient versions of pure functions.xcplaygroundpage │ └── Contents.swift ├── 15 - Concise syntax for sorting using a KeyPath.xcplaygroundpage │ └── Contents.swift ├── 16 - Easier String slicing using ranges.xcplaygroundpage │ └── Contents.swift ├── 17 - Safely subscripting a Collection.xcplaygroundpage │ └── Contents.swift ├── 18 - Comparing Optionals through Conditional Conformance.xcplaygroundpage │ └── Contents.swift ├── 19 - Making good use of #file, #line and #function.xcplaygroundpage │ └── Contents.swift ├── 20 - Running two pieces of code in parallel.xcplaygroundpage │ └── Contents.swift ├── 21 - Measuring execution time with minimum boilerplate.xcplaygroundpage │ └── Contents.swift ├── 22 - Using parallelism to speed-up map().xcplaygroundpage │ └── Contents.swift ├── 23 - Dealing with expirable values.xcplaygroundpage │ └── Contents.swift ├── 24 - A shorter syntax to remove nil values.xcplaygroundpage │ └── Contents.swift ├── 25 - Defining a function to map over dictionaries.xcplaygroundpage │ └── Contents.swift ├── 26 - Retrieving all the necessary data to build a debug view.xcplaygroundpage │ └── Contents.swift ├── 27 - Encapsulating background computation and UI update.xcplaygroundpage │ └── Contents.swift ├── 28 - Shorter syntax to deal with optional strings.xcplaygroundpage │ └── Contents.swift ├── 29 - Removing duplicate values from a Sequence.xcplaygroundpage │ └── Contents.swift ├── 30 - Providing useful operators for Optional booleans.xcplaygroundpage │ └── Contents.swift ├── 31 - Debouncing a function call.xcplaygroundpage │ └── Contents.swift ├── 32 - Performing animations sequentially.xcplaygroundpage │ └── Contents.swift ├── 33 - Small footprint type-erasing with functions.xcplaygroundpage │ └── Contents.swift ├── 34 - Asserting that classes have associated NIBs and vice-versa.xcplaygroundpage │ └── Contents.swift ├── 35 - Defining a union type.xcplaygroundpage │ └── Contents.swift ├── 36 - Avoiding hardcoded reuse identifiers.xcplaygroundpage │ └── Contents.swift ├── 37 - Optimizing the use of `reduce()`.xcplaygroundpage │ └── Contents.swift ├── 38 - Writing an interruptible overload of `forEach`.xcplaygroundpage │ └── Contents.swift ├── 39 - Using `typealias` to its fullest.xcplaygroundpage │ └── Contents.swift ├── 40 - Lightweight data-binding for an MVVM implementation.xcplaygroundpage │ └── Contents.swift ├── 41 - Bringing some type-safety to a userInfo Dictionary.xcplaygroundpage │ └── Contents.swift ├── 42 - Using KeyPaths instead of closures.xcplaygroundpage │ └── Contents.swift ├── 43 - Transform an asynchronous function into a synchronous one.xcplaygroundpage │ └── Contents.swift ├── 44 - Solving callback hell with function composition.xcplaygroundpage │ └── Contents.swift ├── 45 - Getting rid of overabundant `[weak self]` and `guard`.xcplaygroundpage │ └── Contents.swift ├── 46 - Lightweight dependency injection through protocol-oriented programming.xcplaygroundpage │ └── Contents.swift ├── 47 - Another lightweight dependency injection through default values for function parameters.xcplaygroundpage │ └── Contents.swift ├── 48 - Providing a default value to a `Decodable` `enum`.xcplaygroundpage │ └── Contents.swift ├── 49 - Using `Never` to represent impossible code paths.xcplaygroundpage │ └── Contents.swift ├── 50 - Implementing a namespace through an empty `enum`.xcplaygroundpage │ └── Contents.swift ├── 51 - Defining a custom `init` without loosing the compiler-generated one.xcplaygroundpage │ └── Contents.swift ├── 52 - Avoiding double negatives within `guard` statements.xcplaygroundpage │ └── Contents.swift ├── 53 - Using `switch` and `if` as expressions.xcplaygroundpage │ └── Contents.swift ├── 54 - Composing `NSAttributedString` through a Function Builder.xcplaygroundpage │ └── Contents.swift ├── 55 - Implementing pseudo-inheritance between `structs`.xcplaygroundpage │ └── Contents.swift ├── 56 - Localization through `String` interpolation.xcplaygroundpage │ └── Contents.swift └── 57 - Property Wrappers as Debugging Tools.xcplaygroundpage │ └── Contents.swift └── contents.xcplayground /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 Vincent Pradeilles 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Warning 2 | 3 | ⚠️ This repo is a few years old, I've moved my tips collection to my website 👉 [https://www.swiftwithvincent.com/tips](https://www.swiftwithvincent.com/tips) ⚠️ 4 | 5 | # SwiftTips 6 | 7 | The following is a collection of tips I find to be useful when working with the Swift language. More content is available on my [Twitter](https://twitter.com/v_pradeilles) account! 8 | 9 | 📣 NEW 📣 Swift Tips are now available on [YouTube](https://www.youtube.com/playlist?list=PLdXMqVQnoFleH3GSuTUpr3Fjzp1JMy-je) 👇 10 | 11 | [![](https://img.youtube.com/vi/5YGJDsbEVjM/0.jpg)](https://www.youtube.com/watch?v=5YGJDsbEVjM) 12 | 13 | # Summary 14 | 15 | * [#57 Property Wrappers as Debugging Tools](#property-wrappers-as-debugging-tools) 16 | * [#56 Localization through `String` interpolation](#localization-through-string-interpolation) 17 | * [#55 Implementing pseudo-inheritance between `structs`](#implementing-pseudo-inheritance-between-structs) 18 | * [#54 Composing `NSAttributedString` through a Function Builder](#composing-nsattributedstring-through-a-function-builder) 19 | * [#53 Using `switch` and `if` as expressions](#using-switch-and-if-as-expressions) 20 | * [#52 Avoiding double negatives within `guard` statements](#avoiding-double-negatives-within-guard-statements) 21 | * [#51 Defining a custom `init` without loosing the compiler-generated one](#defining-a-custom-init-without-loosing-the-compiler-generated-one) 22 | * [#50 Implementing a namespace through an empty `enum`](#implementing-a-namespace-through-an-empty-enum) 23 | * [#49 Using `Never` to represent impossible code paths](#using-never-to-represent-impossible-code-paths) 24 | * [#48 Providing a default value to a `Decodable` `enum`](#providing-a-default-value-to-a-decodable-enum) 25 | * [#47 Another lightweight dependency injection through default values for function parameters](#another-lightweight-dependency-injection-through-default-values-for-function-parameters) 26 | * [#46 Lightweight dependency injection through protocol-oriented programming](#lightweight-dependency-injection-through-protocol-oriented-programming) 27 | * [#45 Getting rid of overabundant `[weak self]` and `guard`](#getting-rid-of-overabundant-weak-self-and-guard) 28 | * [#44 Solving callback hell with function composition](#solving-callback-hell-with-function-composition) 29 | * [#43 Transform an asynchronous function into a synchronous one](#transform-an-asynchronous-function-into-a-synchronous-one) 30 | * [#42 Using KeyPaths instead of closures](#using-keypaths-instead-of-closures) 31 | * [#41 Bringing some type-safety to a `userInfo` `Dictionary`](#bringing-some-type-safety-to-a-userinfo-dictionary) 32 | * [#40 Lightweight data-binding for an MVVM implementation](#lightweight-data-binding-for-an-mvvm-implementation) 33 | * [#39 Using `typealias` to its fullest](#using-typealias-to-its-fullest) 34 | * [#38 Writing an interruptible overload of `forEach`](#writing-an-interruptible-overload-of-foreach) 35 | * [#37 Optimizing the use of `reduce()`](#optimizing-the-use-of-reduce) 36 | * [#36 Avoiding hardcoded reuse identifiers](#avoiding-hardcoded-reuse-identifiers) 37 | * [#35 Defining a union type](#defining-a-union-type) 38 | * [#34 Asserting that classes have associated NIBs and vice-versa](#asserting-that-classes-have-associated-nibs-and-vice-versa) 39 | * [#33 Small footprint type-erasing with functions](#small-footprint-type-erasing-with-functions) 40 | * [#32 Performing animations sequentially](#performing-animations-sequentially) 41 | * [#31 Debouncing a function call](#debouncing-a-function-call) 42 | * [#30 Providing useful operators for `Optional` booleans](#providing-useful-operators-for-optional-booleans) 43 | * [#29 Removing duplicate values from a `Sequence`](#removing-duplicate-values-from-a-sequence) 44 | * [#28 Shorter syntax to deal with optional strings](#shorter-syntax-to-deal-with-optional-strings) 45 | * [#27 Encapsulating background computation and UI update](#encapsulating-background-computation-and-ui-update) 46 | * [#26 Retrieving all the necessary data to build a debug view](#retrieving-all-the-necessary-data-to-build-a-debug-view) 47 | * [#25 Defining a function to map over dictionaries](#defining-a-function-to-map-over-dictionaries) 48 | * [#24 A shorter syntax to remove `nil` values](#a-shorter-syntax-to-remove-nil-values) 49 | * [#23 Dealing with expirable values](#dealing-with-expirable-values) 50 | * [#22 Using parallelism to speed-up `map()`](#using-parallelism-to-speed-up-map) 51 | * [#21 Measuring execution time with minimum boilerplate](#measuring-execution-time-with-minimum-boilerplate) 52 | * [#20 Running two pieces of code in parallel](#running-two-pieces-of-code-in-parallel) 53 | * [#19 Making good use of #file, #line and #function](#making-good-use-of-file-line-and-function) 54 | * [#18 Comparing Optionals through Conditional Conformance](#comparing-optionals-through-conditional-conformance) 55 | * [#17 Safely subscripting a Collection](#safely-subscripting-a-collection) 56 | * [#16 Easier String slicing using ranges](#easier-string-slicing-using-ranges) 57 | * [#15 Concise syntax for sorting using a KeyPath](#concise-syntax-for-sorting-using-a-keypath) 58 | * [#14 Manufacturing cache-efficient versions of pure functions](#manufacturing-cache-efficient-versions-of-pure-functions) 59 | * [#13 Simplifying complex condition with pattern matching](#simplifying-complex-conditions-with-pattern-matching) 60 | * [#12 Easily generating arrays of data](#easily-generating-arrays-of-data) 61 | * [#11 Using @autoclosure for cleaner call sites](#using-autoclosure-for-cleaner-call-sites) 62 | * [#10 Observing new and old value with RxSwift](#observing-new-and-old-value-with-rxswift) 63 | * [#09 Implicit initialization from literal values](#implicit-initialization-from-literal-values) 64 | * [#08 Achieving systematic validation of data](#achieving-systematic-validation-of-data) 65 | * [#07 Implementing the builder pattern with keypaths](#implementing-the-builder-pattern-with-keypaths) 66 | * [#06 Storing functions rather than values](#storing-functions-rather-than-values) 67 | * [#05 Defining operators on function types](#defining-operators-on-function-types) 68 | * [#04 Typealiases for functions](#typealiases-for-functions) 69 | * [#03 Encapsulating state within a function](#encapsulating-state-within-a-function) 70 | * [#02 Generating all cases for an Enum](#generating-all-cases-for-an-enum) 71 | * [#01 Using map on optional values](#using-map-on-optional-values) 72 | 73 | # Tips 74 | 75 | ## Property Wrappers as Debugging Tools 76 | 77 | Property Wrappers allow developers to wrap properties with specific behaviors, that will be seamlessly triggered whenever the properties are accessed. 78 | 79 | While their primary use case is to implement business logic within our apps, it's also possible to use Property Wrappers as debugging tools! 80 | 81 | For example, we could build a wrapper called `@History`, that would be added to a property while debugging and would keep track of all the values set to this property. 82 | 83 | ```swift 84 | import Foundation 85 | 86 | @propertyWrapper 87 | struct History { 88 | private var value: Value 89 | private(set) var history: [Value] = [] 90 | 91 | init(wrappedValue: Value) { 92 | self.value = wrappedValue 93 | } 94 | 95 | var wrappedValue: Value { 96 | get { value } 97 | 98 | set { 99 | history.append(value) 100 | value = newValue 101 | } 102 | } 103 | 104 | var projectedValue: Self { 105 | return self 106 | } 107 | } 108 | 109 | // We can then decorate our business code 110 | // with the `@History` wrapper 111 | struct User { 112 | @History var name: String = "" 113 | } 114 | 115 | var user = User() 116 | 117 | // All the existing call sites will still 118 | // compile, without the need for any change 119 | user.name = "John" 120 | user.name = "Jane" 121 | 122 | // But now we can also access an history of 123 | // all the previous values! 124 | user.$name.history // ["", "John"] 125 | ``` 126 | 127 | ## Localization through `String` interpolation 128 | 129 | Swift 5 gave us the possibility to define our own custom `String` interpolation methods. 130 | 131 | This feature can be used to power many use cases, but there is one that is guaranteed to make sense in most projects: localizing user-facing strings. 132 | 133 | ```swift 134 | import Foundation 135 | 136 | extension String.StringInterpolation { 137 | mutating func appendInterpolation(localized key: String, _ args: CVarArg...) { 138 | let localized = String(format: NSLocalizedString(key, comment: ""), arguments: args) 139 | appendLiteral(localized) 140 | } 141 | } 142 | 143 | 144 | /* 145 | Let's assume that this is the content of our Localizable.strings: 146 | 147 | "welcome.screen.greetings" = "Hello %@!"; 148 | */ 149 | 150 | let userName = "John" 151 | print("\(localized: "welcome.screen.greetings", userName)") // Hello John! 152 | ``` 153 | 154 | ## Implementing pseudo-inheritance between `structs` 155 | 156 | If you’ve always wanted to use some kind of inheritance mechanism for your structs, Swift 5.1 is going to make you very happy! 157 | 158 | Using the new KeyPath-based dynamic member lookup, you can implement some pseudo-inheritance, where a type inherits the API of another one 🎉 159 | 160 | (However, be careful, I’m definitely not advocating inheritance as a go-to solution 🙃) 161 | 162 | ```swift 163 | import Foundation 164 | 165 | protocol Inherits { 166 | associatedtype SuperType 167 | 168 | var `super`: SuperType { get } 169 | } 170 | 171 | extension Inherits { 172 | subscript(dynamicMember keyPath: KeyPath) -> T { 173 | return self.`super`[keyPath: keyPath] 174 | } 175 | } 176 | 177 | struct Person { 178 | let name: String 179 | } 180 | 181 | @dynamicMemberLookup 182 | struct User: Inherits { 183 | let `super`: Person 184 | 185 | let login: String 186 | let password: String 187 | } 188 | 189 | let user = User(super: Person(name: "John Appleseed"), login: "Johnny", password: "1234") 190 | 191 | user.name // "John Appleseed" 192 | user.login // "Johnny" 193 | ``` 194 | 195 | ## Composing `NSAttributedString` through a Function Builder 196 | 197 | Swift 5.1 introduced Function Builders: a great tool for building custom DSL syntaxes, like SwiftUI. However, one doesn't need to be building a full-fledged DSL in order to leverage them. 198 | 199 | For example, it's possible to write a simple Function Builder, whose job will be to compose together individual instances of `NSAttributedString` through a nicer syntax than the standard API. 200 | 201 | ```swift 202 | import UIKit 203 | 204 | @_functionBuilder 205 | class NSAttributedStringBuilder { 206 | static func buildBlock(_ components: NSAttributedString...) -> NSAttributedString { 207 | let result = NSMutableAttributedString(string: "") 208 | 209 | return components.reduce(into: result) { (result, current) in result.append(current) } 210 | } 211 | } 212 | 213 | extension NSAttributedString { 214 | class func composing(@NSAttributedStringBuilder _ parts: () -> NSAttributedString) -> NSAttributedString { 215 | return parts() 216 | } 217 | } 218 | 219 | let result = NSAttributedString.composing { 220 | NSAttributedString(string: "Hello", 221 | attributes: [.font: UIFont.systemFont(ofSize: 24), 222 | .foregroundColor: UIColor.red]) 223 | NSAttributedString(string: " world!", 224 | attributes: [.font: UIFont.systemFont(ofSize: 20), 225 | .foregroundColor: UIColor.orange]) 226 | } 227 | ``` 228 | 229 | ## Using `switch` and `if` as expressions 230 | 231 | Contrary to other languages, like Kotlin, Swift does not allow `switch` and `if` to be used as expressions. Meaning that the following code is not valid Swift: 232 | 233 | ```swift 234 | let constant = if condition { 235 | someValue 236 | } else { 237 | someOtherValue 238 | } 239 | ``` 240 | 241 | A common solution to this problem is to wrap the `if` or `switch` statement within a closure, that will then be immediately called. While this approach does manage to achieve the desired goal, it makes for a rather poor syntax. 242 | 243 | To avoid the ugly trailing `()` and improve on the readability, you can define a `resultOf` function, that will serve the exact same purpose, in a more elegant way. 244 | 245 | ```swift 246 | import Foundation 247 | 248 | func resultOf(_ code: () -> T) -> T { 249 | return code() 250 | } 251 | 252 | let randomInt = Int.random(in: 0...3) 253 | 254 | let spelledOut: String = resultOf { 255 | switch randomInt { 256 | case 0: 257 | return "Zero" 258 | case 1: 259 | return "One" 260 | case 2: 261 | return "Two" 262 | case 3: 263 | return "Three" 264 | default: 265 | return "Out of range" 266 | } 267 | } 268 | 269 | print(spelledOut) 270 | ``` 271 | 272 | ## Avoiding double negatives within `guard` statements 273 | 274 | A `guard` statement is a very convenient way for the developer to assert that a condition is met, in order for the execution of the program to keep going. 275 | 276 | However, since the body of a `guard` statement is meant to be executed when the condition evaluates to `false`, the use of the negation (`!`) operator within the condition of a `guard` statement can make the code hard to read, as it becomes a double negative. 277 | 278 | A nice trick to avoid such double negatives is to encapsulate the use of the `!` operator within a new property or function, whose name does not include a negative. 279 | 280 | ```swift 281 | import Foundation 282 | 283 | extension Collection { 284 | var hasElements: Bool { 285 | return !isEmpty 286 | } 287 | } 288 | 289 | let array = Bool.random() ? [1, 2, 3] : [] 290 | 291 | guard array.hasElements else { fatalError("array was empty") } 292 | 293 | print(array) 294 | ``` 295 | 296 | ## Defining a custom `init` without loosing the compiler-generated one 297 | 298 | It's common knowledge for Swift developers that, when you define a `struct`, the compiler is going to automatically generate a memberwise `init` for you. That is, unless you also define an `init` of your own. Because then, the compiler won't generate any memberwise `init`. 299 | 300 | Yet, there are many instances where we might enjoy the opportunity to get both. As it turns out, this goal is quite easy to achieve: you just need to define your own `init` in an `extension` rather than inside the type definition itself. 301 | 302 | ```swift 303 | import Foundation 304 | 305 | struct Point { 306 | let x: Int 307 | let y: Int 308 | } 309 | 310 | extension Point { 311 | init() { 312 | x = 0 313 | y = 0 314 | } 315 | } 316 | 317 | let usingDefaultInit = Point(x: 4, y: 3) 318 | let usingCustomInit = Point() 319 | ``` 320 | 321 | [![](https://img.youtube.com/vi/IBQX3beJKiM/0.jpg)](https://www.youtube.com/watch?v=IBQX3beJKiM) 322 | 323 | ## Implementing a namespace through an empty `enum` 324 | 325 | Swift does not really have an out-of-the-box support of namespaces. One could argue that a Swift module can be seen as a namespace, but creating a dedicated Framework for this sole purpose can legitimately be regarded as overkill. 326 | 327 | Some developers have taken the habit to use a `struct` which only contains `static` fields to implement a namespace. While this does the job, it requires us to remember to implement an empty `private` `init()`, because it wouldn't make sense for such a `struct` to be instantiated. 328 | 329 | It's actually possible to take this approach one step further, by replacing the `struct` with an `enum`. While it might seem weird to have an `enum` with no `case`, it's actually a [very idiomatic way](https://github.com/apple/swift/blob/a4230ab2ad37e37edc9ed86cd1510b7c016a769d/stdlib/public/core/Unicode.swift#L918) to declare a type that cannot be instantiated. 330 | 331 | ```swift 332 | import Foundation 333 | 334 | enum NumberFormatterProvider { 335 | static var currencyFormatter: NumberFormatter { 336 | let formatter = NumberFormatter() 337 | formatter.numberStyle = .currency 338 | formatter.roundingIncrement = 0.01 339 | return formatter 340 | } 341 | 342 | static var decimalFormatter: NumberFormatter { 343 | let formatter = NumberFormatter() 344 | formatter.numberStyle = .decimal 345 | formatter.decimalSeparator = "," 346 | return formatter 347 | } 348 | } 349 | 350 | NumberFormatterProvider() // ❌ impossible to instantiate by mistake 351 | 352 | NumberFormatterProvider.currencyFormatter.string(from: 2.456) // $2.46 353 | NumberFormatterProvider.decimalFormatter.string(from: 2.456) // 2,456 354 | ``` 355 | 356 | ## Using `Never` to represent impossible code paths 357 | 358 | `Never` is quite a peculiar type in the Swift Standard Library: it is defined as an empty enum `enum Never { }`. 359 | 360 | While this might seem odd at first glance, it actually yields a very interesting property: it makes it a type that cannot be constructed (i.e. it possesses no instances). 361 | 362 | This way, `Never` can be used as a generic parameter to let the compiler know that a particular feature will not be used. 363 | 364 | ```swift 365 | import Foundation 366 | 367 | enum Result { 368 | case success(value: Value) 369 | case failure(error: Error) 370 | } 371 | 372 | func willAlwaysSucceed(_ completion: @escaping ((Result) -> Void)) { 373 | completion(.success(value: "Call was successful")) 374 | } 375 | 376 | willAlwaysSucceed( { result in 377 | switch result { 378 | case .success(let value): 379 | print(value) 380 | // the compiler knows that the `failure` case cannot happen 381 | // so it doesn't require us to handle it. 382 | } 383 | }) 384 | ``` 385 | 386 | ## Providing a default value to a `Decodable` `enum` 387 | 388 | Swift's `Codable` framework does a great job at seamlessly decoding entities from a JSON stream. However, when we integrate web-services, we are sometimes left to deal with JSONs that require behaviors that `Codable` does not provide out-of-the-box. 389 | 390 | For instance, we might have a string-based or integer-based `enum`, and be required to set it to a default value when the data found in the JSON does not match any of its cases. 391 | 392 | We might be tempted to implement this via an extensive `switch` statement over all the possible cases, but there is a much shorter alternative through the initializer `init?(rawValue:)`: 393 | 394 | ```swift 395 | import Foundation 396 | 397 | enum State: String, Decodable { 398 | case active 399 | case inactive 400 | case undefined 401 | 402 | init(from decoder: Decoder) throws { 403 | let container = try decoder.singleValueContainer() 404 | let decodedString = try container.decode(String.self) 405 | 406 | self = State(rawValue: decodedString) ?? .undefined 407 | } 408 | } 409 | 410 | let data = """ 411 | ["active", "inactive", "foo"] 412 | """.data(using: .utf8)! 413 | 414 | let decoded = try! JSONDecoder().decode([State].self, from: data) 415 | 416 | print(decoded) // [State.active, State.inactive, State.undefined] 417 | ``` 418 | 419 | ## Another lightweight dependency injection through default values for function parameters 420 | 421 | Dependency injection boils down to a simple idea: when an object requires a dependency, it shouldn't create it by itself, but instead it should be given a function that does it for him. 422 | 423 | Now the great thing with Swift is that, not only can a function take another function as a parameter, but that parameter can also be given a default value. 424 | 425 | When you combine both those features, you can end up with a dependency injection pattern that is both lightweight on boilerplate, but also type safe. 426 | 427 | ```swift 428 | import Foundation 429 | 430 | protocol Service { 431 | func call() -> String 432 | } 433 | 434 | class ProductionService: Service { 435 | func call() -> String { 436 | return "This is the production" 437 | } 438 | } 439 | 440 | class MockService: Service { 441 | func call() -> String { 442 | return "This is a mock" 443 | } 444 | } 445 | 446 | typealias Provider = () -> T 447 | 448 | class Controller { 449 | 450 | let service: Service 451 | 452 | init(serviceProvider: Provider = { return ProductionService() }) { 453 | self.service = serviceProvider() 454 | } 455 | 456 | func work() { 457 | print(service.call()) 458 | } 459 | } 460 | 461 | let productionController = Controller() 462 | productionController.work() // prints "This is the production" 463 | 464 | let mockedController = Controller(serviceProvider: { return MockService() }) 465 | mockedController.work() // prints "This is a mock" 466 | ``` 467 | 468 | ## Lightweight dependency injection through protocol-oriented programming 469 | 470 | Singletons are pretty bad. They make your architecture rigid and tightly coupled, which then results in your code being hard to test and refactor. Instead of using singletons, your code should rely on dependency injection, which is a much more architecturally sound approach. 471 | 472 | But singletons are so easy to use, and dependency injection requires us to do extra-work. So maybe, for simple situations, we could find an in-between solution? 473 | 474 | One possible solution is to rely on one of Swift's most know features: protocol-oriented programming. Using a `protocol`, we declare and access our dependency. We then store it in a private singleton, and perform the injection through an extension of said `protocol`. 475 | 476 | This way, our code will indeed be decoupled from its dependency, while at the same time keeping the boilerplate to a minimum. 477 | 478 | ```swift 479 | import Foundation 480 | 481 | protocol Formatting { 482 | var formatter: NumberFormatter { get } 483 | } 484 | 485 | private let sharedFormatter: NumberFormatter = { 486 | let sharedFormatter = NumberFormatter() 487 | sharedFormatter.numberStyle = .currency 488 | return sharedFormatter 489 | }() 490 | 491 | extension Formatting { 492 | var formatter: NumberFormatter { return sharedFormatter } 493 | } 494 | 495 | class ViewModel: Formatting { 496 | var displayableAmount: String? 497 | 498 | func updateDisplay(to amount: Double) { 499 | displayableAmount = formatter.string(for: amount) 500 | } 501 | } 502 | 503 | let viewModel = ViewModel() 504 | 505 | viewModel.updateDisplay(to: 42000.45) 506 | viewModel.displayableAmount // "$42,000.45" 507 | ``` 508 | 509 | ## Getting rid of overabundant `[weak self]` and `guard` 510 | 511 | Callbacks are a part of almost all iOS apps, and as frameworks such as `RxSwift` keep gaining in popularity, they become ever more present in our codebase. 512 | 513 | Seasoned Swift developers are aware of the potential memory leaks that `@escaping` callbacks can produce, so they make real sure to always use `[weak self]`, whenever they need to use `self` inside such a context. And when they need to have `self` be non-optional, they then add a `guard` statement along. 514 | 515 | Consequently, this syntax of a `[weak self]` followed by a `guard` rapidly tends to appear everywhere in the codebase. The good thing is that, through a little protocol-oriented trick, it's actually possible to get rid of this tedious syntax, without loosing any of its benefits! 516 | 517 | ```swift 518 | import Foundation 519 | import PlaygroundSupport 520 | 521 | PlaygroundPage.current.needsIndefiniteExecution = true 522 | 523 | protocol Weakifiable: class { } 524 | 525 | extension Weakifiable { 526 | func weakify(_ code: @escaping (Self) -> Void) -> () -> Void { 527 | return { [weak self] in 528 | guard let self = self else { return } 529 | 530 | code(self) 531 | } 532 | } 533 | 534 | func weakify(_ code: @escaping (T, Self) -> Void) -> (T) -> Void { 535 | return { [weak self] arg in 536 | guard let self = self else { return } 537 | 538 | code(arg, self) 539 | } 540 | } 541 | } 542 | 543 | extension NSObject: Weakifiable { } 544 | 545 | class Producer: NSObject { 546 | 547 | deinit { 548 | print("deinit Producer") 549 | } 550 | 551 | private var handler: (Int) -> Void = { _ in } 552 | 553 | func register(handler: @escaping (Int) -> Void) { 554 | self.handler = handler 555 | 556 | DispatchQueue.main.asyncAfter(deadline: .now() + 1.0, execute: { self.handler(42) }) 557 | } 558 | } 559 | 560 | class Consumer: NSObject { 561 | 562 | deinit { 563 | print("deinit Consumer") 564 | } 565 | 566 | let producer = Producer() 567 | 568 | func consume() { 569 | producer.register(handler: weakify { result, strongSelf in 570 | strongSelf.handle(result) 571 | }) 572 | } 573 | 574 | private func handle(_ result: Int) { 575 | print("🎉 \(result)") 576 | } 577 | } 578 | 579 | var consumer: Consumer? = Consumer() 580 | 581 | consumer?.consume() 582 | 583 | DispatchQueue.main.asyncAfter(deadline: .now() + 2.0, execute: { consumer = nil }) 584 | 585 | // This code prints: 586 | // 🎉 42 587 | // deinit Consumer 588 | // deinit Producer 589 | ``` 590 | 591 | ## Solving callback hell with function composition 592 | 593 | Asynchronous functions are a big part of iOS APIs, and most developers are familiar with the challenge they pose when one needs to sequentially call several asynchronous APIs. 594 | 595 | This often results in callbacks being nested into one another, a predicament often referred to as callback hell. 596 | 597 | Many third-party frameworks are able to tackle this issue, for instance [RxSwift](https://github.com/ReactiveX/RxSwift) or [PromiseKit](https://github.com/mxcl/PromiseKit). Yet, for simple instances of the problem, there is no need to use such big guns, as it can actually be solved with simple function composition. 598 | 599 | ```swift 600 | import Foundation 601 | 602 | typealias CompletionHandler = (Result?, Error?) -> Void 603 | 604 | infix operator ~>: MultiplicationPrecedence 605 | 606 | func ~> (_ first: @escaping (CompletionHandler) -> Void, _ second: @escaping (T, CompletionHandler) -> Void) -> (CompletionHandler) -> Void { 607 | return { completion in 608 | first({ firstResult, error in 609 | guard let firstResult = firstResult else { completion(nil, error); return } 610 | 611 | second(firstResult, { (secondResult, error) in 612 | completion(secondResult, error) 613 | }) 614 | }) 615 | } 616 | } 617 | 618 | func ~> (_ first: @escaping (CompletionHandler) -> Void, _ transform: @escaping (T) -> U) -> (CompletionHandler) -> Void { 619 | return { completion in 620 | first({ result, error in 621 | guard let result = result else { completion(nil, error); return } 622 | 623 | completion(transform(result), nil) 624 | }) 625 | } 626 | } 627 | 628 | func service1(_ completionHandler: CompletionHandler) { 629 | completionHandler(42, nil) 630 | } 631 | 632 | func service2(arg: String, _ completionHandler: CompletionHandler) { 633 | completionHandler("🎉 \(arg)", nil) 634 | } 635 | 636 | let chainedServices = service1 637 | ~> { int in return String(int / 2) } 638 | ~> service2 639 | 640 | chainedServices({ result, _ in 641 | guard let result = result else { return } 642 | 643 | print(result) // Prints: 🎉 21 644 | }) 645 | ``` 646 | 647 | ## Transform an asynchronous function into a synchronous one 648 | 649 | Asynchronous functions are a great way to deal with future events without blocking a thread. Yet, there are times where we would like them to behave in exactly such a blocking way. 650 | 651 | Think about writing unit tests and using mocked network calls. You will need to add complexity to your test in order to deal with asynchronous functions, whereas synchronous ones would be much easier to manage. 652 | 653 | Thanks to Swift proficiency in the functional paradigm, it is possible to write a function whose job is to take an asynchronous function and transform it into a synchronous one. 654 | 655 | ```swift 656 | import Foundation 657 | 658 | func makeSynchrone(_ asyncFunction: @escaping (A, (B) -> Void) -> Void) -> (A) -> B { 659 | return { arg in 660 | let lock = NSRecursiveLock() 661 | 662 | var result: B? = nil 663 | 664 | asyncFunction(arg) { 665 | result = $0 666 | lock.unlock() 667 | } 668 | 669 | lock.lock() 670 | 671 | return result! 672 | } 673 | } 674 | 675 | func myAsyncFunction(arg: Int, completionHandler: (String) -> Void) { 676 | completionHandler("🎉 \(arg)") 677 | } 678 | 679 | let syncFunction = makeSynchrone(myAsyncFunction) 680 | 681 | print(syncFunction(42)) // prints 🎉 42 682 | ``` 683 | 684 | ## Using KeyPaths instead of closures 685 | 686 | Closures are a great way to interact with generic APIs, for instance APIs that allow to manipulate data structures through the use of generic functions, such as `filter()` or `sorted()`. 687 | 688 | The annoying part is that closures tend to clutter your code with many instances of `{`, `}` and `$0`, which can quickly undermine its readably. 689 | 690 | A nice alternative for a cleaner syntax is to use a `KeyPath` instead of a closure, along with an operator that will deal with transforming the provided `KeyPath` in a closure. 691 | 692 | ```swift 693 | import Foundation 694 | 695 | prefix operator ^ 696 | 697 | prefix func ^ (_ keyPath: KeyPath) -> (Element) -> Attribute { 698 | return { element in element[keyPath: keyPath] } 699 | } 700 | 701 | struct MyData { 702 | let int: Int 703 | let string: String 704 | } 705 | 706 | let data = [MyData(int: 2, string: "Foo"), MyData(int: 4, string: "Bar")] 707 | 708 | data.map(^\.int) // [2, 4] 709 | data.map(^\.string) // ["Foo", "Bar"] 710 | ``` 711 | 712 | [![](https://img.youtube.com/vi/vnsKOxOrXnY/0.jpg)](https://www.youtube.com/watch?v=vnsKOxOrXnY) 713 | 714 | ## Bringing some type-safety to a `userInfo` `Dictionary` 715 | 716 | Many iOS APIs still rely on a `userInfo` `Dictionary` to handle use-case specific data. This `Dictionary` usually stores untyped values, and is declared as follows: `[String: Any]` (or sometimes `[AnyHashable: Any]`. 717 | 718 | Retrieving data from such a structure will involve some conditional casting (via the `as?` operator), which is prone to both errors and repetitions. Yet, by introducing a custom `subscript`, it's possible to encapsulate all the tedious logic, and end-up with an easier and more robust API. 719 | 720 | ```swift 721 | import Foundation 722 | 723 | typealias TypedUserInfoKey = (key: String, type: T.Type) 724 | 725 | extension Dictionary where Key == String, Value == Any { 726 | subscript(_ typedKey: TypedUserInfoKey) -> T? { 727 | return self[typedKey.key] as? T 728 | } 729 | } 730 | 731 | let userInfo: [String : Any] = ["Foo": 4, "Bar": "forty-two"] 732 | 733 | let integerTypedKey = TypedUserInfoKey(key: "Foo", type: Int.self) 734 | let intValue = userInfo[integerTypedKey] // returns 4 735 | type(of: intValue) // returns Int? 736 | 737 | let stringTypedKey = TypedUserInfoKey(key: "Bar", type: String.self) 738 | let stringValue = userInfo[stringTypedKey] // returns "forty-two" 739 | type(of: stringValue) // returns String? 740 | ``` 741 | 742 | ## Lightweight data-binding for an MVVM implementation 743 | 744 | MVVM is a great pattern to separate business logic from presentation logic. The main challenge to make it work, is to define a mechanism for the presentation layer to be notified of model updates. 745 | 746 | [RxSwift](https://github.com/ReactiveX/RxSwift) is a perfect choice to solve such a problem. Yet, some developers don't feel confortable with leveraging a third-party library for such a central part of their architecture. 747 | 748 | For those situation, it's possible to define a lightweight `Variable` type, that will make the MVVM pattern very easy to use! 749 | 750 | ```swift 751 | import Foundation 752 | 753 | class Variable { 754 | var value: Value { 755 | didSet { 756 | onUpdate?(value) 757 | } 758 | } 759 | 760 | var onUpdate: ((Value) -> Void)? { 761 | didSet { 762 | onUpdate?(value) 763 | } 764 | } 765 | 766 | init(_ value: Value, _ onUpdate: ((Value) -> Void)? = nil) { 767 | self.value = value 768 | self.onUpdate = onUpdate 769 | self.onUpdate?(value) 770 | } 771 | } 772 | 773 | let variable: Variable = Variable(nil) 774 | 775 | variable.onUpdate = { data in 776 | if let data = data { 777 | print(data) 778 | } 779 | } 780 | 781 | variable.value = "Foo" 782 | variable.value = "Bar" 783 | 784 | // prints: 785 | // Foo 786 | // Bar 787 | ``` 788 | 789 | ## Using `typealias` to its fullest 790 | 791 | The keyword `typealias` allows developers to give a new name to an already existing type. For instance, Swift defines `Void` as a `typealias` of `()`, the empty tuple. 792 | 793 | But a less known feature of this mechanism is that it allows to assign concrete types for generic parameters, or to rename them. This can help make the semantics of generic types much clearer, when used in specific use cases. 794 | 795 | ```swift 796 | import Foundation 797 | 798 | enum Either { 799 | case left(Left) 800 | case right(Right) 801 | } 802 | 803 | typealias Result = Either 804 | 805 | typealias IntOrString = Either 806 | ``` 807 | 808 | [![](https://img.youtube.com/vi/Z4ji0dpAkJA/0.jpg)](https://www.youtube.com/watch?v=Z4ji0dpAkJA) 809 | 810 | ## Writing an interruptible overload of `forEach` 811 | 812 | Iterating through objects via the `forEach(_:)` method is a great alternative to the classic `for` loop, as it allows our code to be completely oblivious of the iteration logic. One limitation, however, is that `forEach(_:)` does not allow to stop the iteration midway. 813 | 814 | Taking inspiration from the [Objective-C implementation](https://developer.apple.com/documentation/foundation/nsarray/1415846-enumerateobjectsusingblock), we can write an overload that will allow the developer to stop the iteration, if needed. 815 | 816 | ```swift 817 | import Foundation 818 | 819 | extension Sequence { 820 | func forEach(_ body: (Element, _ stop: inout Bool) throws -> Void) rethrows { 821 | var stop = false 822 | for element in self { 823 | try body(element, &stop) 824 | 825 | if stop { 826 | return 827 | } 828 | } 829 | } 830 | } 831 | 832 | ["Foo", "Bar", "FooBar"].forEach { element, stop in 833 | print(element) 834 | stop = (element == "Bar") 835 | } 836 | 837 | // Prints: 838 | // Foo 839 | // Bar 840 | ``` 841 | 842 | ## Optimizing the use of `reduce()` 843 | 844 | Functional programing is a great way to simplify a codebase. For instance, `reduce` is an alternative to the classic `for` loop, without most the boilerplate. Unfortunately, simplicity often comes at the price of performance. 845 | 846 | Consider that you want to remove duplicate values from a `Sequence`. While `reduce()` is a perfectly fine way to express this computation, the performance will be sub optimal, because of all the unnecessary `Array` copying that will happen every time its closure gets called. 847 | 848 | That's when `reduce(into:_:)` comes into play. This version of `reduce` leverages the capacities of copy-on-write type (such as `Array` or `Dictionnary`) in order to avoid unnecessary copying, which results in a great performance boost. 849 | 850 | ```swift 851 | import Foundation 852 | 853 | func time(averagedExecutions: Int = 1, _ code: () -> Void) { 854 | let start = Date() 855 | for _ in 0..(_ class: T.Type) { 901 | register(`class`, forCellReuseIdentifier: T.reuseIdentifier) 902 | } 903 | func dequeueReusableCell(for indexPath: IndexPath) -> T { 904 | return dequeueReusableCell(withIdentifier: T.reuseIdentifier, for: indexPath) as! T 905 | } 906 | } 907 | 908 | class MyCell: UITableViewCell { } 909 | 910 | let tableView = UITableView() 911 | 912 | tableView.register(MyCell.self) 913 | let myCell: MyCell = tableView.dequeueReusableCell(for: [0, 0]) 914 | ``` 915 | 916 | ## Defining a union type 917 | 918 | The C language has a construct called `union`, that allows a single variable to hold values from different types. While Swift does not provide such a construct, it provides enums with associated values, which allows us to define a type called `Either` that implements a `union` of two types. 919 | 920 | ```swift 921 | import Foundation 922 | 923 | enum Either { 924 | case left(A) 925 | case right(B) 926 | 927 | func either(ifLeft: ((A) -> Void)? = nil, ifRight: ((B) -> Void)? = nil) { 928 | switch self { 929 | case let .left(a): 930 | ifLeft?(a) 931 | case let .right(b): 932 | ifRight?(b) 933 | } 934 | } 935 | } 936 | 937 | extension Bool { static func random() -> Bool { return arc4random_uniform(2) == 0 } } 938 | 939 | var intOrString: Either = Bool.random() ? .left(2) : .right("Foo") 940 | 941 | intOrString.either(ifLeft: { print($0 + 1) }, ifRight: { print($0 + "Bar") }) 942 | ``` 943 | 944 | If you're interested by this kind of data structure, I strongly recommend that you learn more about [Algebraic Data Types](https://en.wikipedia.org/wiki/Algebraic_data_type). 945 | 946 | ## Asserting that classes have associated NIBs and vice-versa 947 | 948 | Most of the time, when we create a `.xib` file, we give it the same name as its associated class. From that, if we later refactor our code and rename such a class, we run the risk of forgetting to rename the associated `.xib`. 949 | 950 | While the error will often be easy to catch, if the `.xib` is used in a remote section of its app, it might go unnoticed for sometime. Fortunately it's possible to build custom test predicates that will assert that 1) for a given class, there exists a `.nib` with the same name in a given `Bundle`, 2) for all the `.nib` in a given `Bundle`, there exists a class with the same name. 951 | 952 | ```swift 953 | import XCTest 954 | 955 | public func XCTAssertClassHasNib(_ class: AnyClass, bundle: Bundle, file: StaticString = #file, line: UInt = #line) { 956 | let associatedNibURL = bundle.url(forResource: String(describing: `class`), withExtension: "nib") 957 | 958 | XCTAssertNotNil(associatedNibURL, "Class \"\(`class`)\" has no associated nib file", file: file, line: line) 959 | } 960 | 961 | public func XCTAssertNibHaveClasses(_ bundle: Bundle, file: StaticString = #file, line: UInt = #line) { 962 | guard let bundleName = bundle.infoDictionary?["CFBundleName"] as? String, 963 | let basePath = bundle.resourcePath, 964 | let enumerator = FileManager.default.enumerator(at: URL(fileURLWithPath: basePath), 965 | includingPropertiesForKeys: nil, 966 | options: [.skipsHiddenFiles, .skipsSubdirectoryDescendants]) else { return } 967 | 968 | var nibFilesURLs = [URL]() 969 | 970 | for case let fileURL as URL in enumerator { 971 | if fileURL.pathExtension.uppercased() == "NIB" { 972 | nibFilesURLs.append(fileURL) 973 | } 974 | } 975 | 976 | nibFilesURLs.map { $0.lastPathComponent } 977 | .compactMap { $0.split(separator: ".").first } 978 | .map { String($0) } 979 | .forEach { 980 | let associatedClass: AnyClass? = bundle.classNamed("\(bundleName).\($0)") 981 | 982 | XCTAssertNotNil(associatedClass, "File \"\($0).nib\" has no associated class", file: file, line: line) 983 | } 984 | } 985 | 986 | XCTAssertClassHasNib(MyFirstTableViewCell.self, bundle: Bundle(for: AppDelegate.self)) 987 | XCTAssertClassHasNib(MySecondTableViewCell.self, bundle: Bundle(for: AppDelegate.self)) 988 | 989 | XCTAssertNibHaveClasses(Bundle(for: AppDelegate.self)) 990 | ``` 991 | 992 | Many thanks [Benjamin Lavialle](https://www.linkedin.com/in/benjamin-lavialle-0a184140/) for coming up with the idea behind the second test predicate. 993 | 994 | ## Small footprint type-erasing with functions 995 | 996 | Seasoned Swift developers know it: a protocol with associated type (PAT) "can only be used as a generic constraint because it has Self or associated type requirements". When we really need to use a PAT to type a variable, the goto workaround is to use a [type-erased wrapper](https://academy.realm.io/posts/type-erased-wrappers-in-swift/). 997 | 998 | While this solution works perfectly, it requires a fair amount of boilerplate code. In instances where we are only interested in exposing one particular function of the PAT, a shorter approach using function types is possible. 999 | 1000 | ```swift 1001 | import Foundation 1002 | import UIKit 1003 | 1004 | protocol Configurable { 1005 | associatedtype Model 1006 | 1007 | func configure(with model: Model) 1008 | } 1009 | 1010 | typealias Configurator = (Model) -> () 1011 | 1012 | extension UILabel: Configurable { 1013 | func configure(with model: String) { 1014 | self.text = model 1015 | } 1016 | } 1017 | 1018 | let label = UILabel() 1019 | let configurator: Configurator = label.configure 1020 | 1021 | configurator("Foo") 1022 | 1023 | label.text // "Foo" 1024 | ``` 1025 | 1026 | ## Performing animations sequentially 1027 | 1028 | `UIKit` exposes a very powerful and simple API to perform view animations. However, this API can become a little bit quirky to use when we want to perform animations sequentially, because it involves nesting closure within one another, which produces notoriously hard to maintain code. 1029 | 1030 | Nonetheless, it's possible to define a rather simple class, that will expose a really nicer API for this particular use case 👌 1031 | 1032 | ```swift 1033 | import Foundation 1034 | import UIKit 1035 | 1036 | class AnimationSequence { 1037 | typealias Animations = () -> Void 1038 | 1039 | private let current: Animations 1040 | private let duration: TimeInterval 1041 | private var next: AnimationSequence? = nil 1042 | 1043 | init(animations: @escaping Animations, duration: TimeInterval) { 1044 | self.current = animations 1045 | self.duration = duration 1046 | } 1047 | 1048 | @discardableResult func append(animations: @escaping Animations, duration: TimeInterval) -> AnimationSequence { 1049 | var lastAnimation = self 1050 | while let nextAnimation = lastAnimation.next { 1051 | lastAnimation = nextAnimation 1052 | } 1053 | lastAnimation.next = AnimationSequence(animations: animations, duration: duration) 1054 | return self 1055 | } 1056 | 1057 | func run() { 1058 | UIView.animate(withDuration: duration, animations: current, completion: { finished in 1059 | if finished, let next = self.next { 1060 | next.run() 1061 | } 1062 | }) 1063 | } 1064 | } 1065 | 1066 | var firstView = UIView() 1067 | var secondView = UIView() 1068 | 1069 | firstView.alpha = 0 1070 | secondView.alpha = 0 1071 | 1072 | AnimationSequence(animations: { firstView.alpha = 1.0 }, duration: 1) 1073 | .append(animations: { secondView.alpha = 1.0 }, duration: 0.5) 1074 | .append(animations: { firstView.alpha = 0.0 }, duration: 2.0) 1075 | .run() 1076 | ``` 1077 | 1078 | ## Debouncing a function call 1079 | 1080 | Debouncing is a very useful tool when dealing with UI inputs. Consider a search bar, whose content is used to query an API. It wouldn't make sense to perform a request for every character the user is typing, because as soon as a new character is entered, the result of the previous request has become irrelevant. 1081 | 1082 | Instead, our code will perform much better if we "debounce" the API call, meaning that we will wait until some delay has passed, without the input being modified, before actually performing the call. 1083 | 1084 | ```swift 1085 | import Foundation 1086 | 1087 | func debounced(delay: TimeInterval, queue: DispatchQueue = .main, action: @escaping (() -> Void)) -> () -> Void { 1088 | var workItem: DispatchWorkItem? 1089 | 1090 | return { 1091 | workItem?.cancel() 1092 | workItem = DispatchWorkItem(block: action) 1093 | queue.asyncAfter(deadline: .now() + delay, execute: workItem!) 1094 | } 1095 | } 1096 | 1097 | let debouncedPrint = debounced(delay: 1.0) { print("Action performed!") } 1098 | 1099 | debouncedPrint() 1100 | debouncedPrint() 1101 | debouncedPrint() 1102 | 1103 | // After a 1 second delay, this gets 1104 | // printed only once to the console: 1105 | 1106 | // Action performed! 1107 | ``` 1108 | 1109 | ## Providing useful operators for `Optional` booleans 1110 | 1111 | When we need to apply the standard boolean operators to `Optional` booleans, we often end up with a syntax unnecessarily crowded with unwrapping operations. By taking a cue from the world of [three-valued logics](https://en.wikipedia.org/wiki/Three-valued_logic), we can define a couple operators that make working with `Bool?` values much nicer. 1112 | 1113 | ```swift 1114 | import Foundation 1115 | 1116 | func && (lhs: Bool?, rhs: Bool?) -> Bool? { 1117 | switch (lhs, rhs) { 1118 | case (false, _), (_, false): 1119 | return false 1120 | case let (unwrapLhs?, unwrapRhs?): 1121 | return unwrapLhs && unwrapRhs 1122 | default: 1123 | return nil 1124 | } 1125 | } 1126 | 1127 | func || (lhs: Bool?, rhs: Bool?) -> Bool? { 1128 | switch (lhs, rhs) { 1129 | case (true, _), (_, true): 1130 | return true 1131 | case let (unwrapLhs?, unwrapRhs?): 1132 | return unwrapLhs || unwrapRhs 1133 | default: 1134 | return nil 1135 | } 1136 | } 1137 | 1138 | false && nil // false 1139 | true && nil // nil 1140 | [true, nil, false].reduce(true, &&) // false 1141 | 1142 | nil || true // true 1143 | nil || false // nil 1144 | [true, nil, false].reduce(false, ||) // true 1145 | ``` 1146 | 1147 | ## Removing duplicate values from a `Sequence` 1148 | 1149 | Transforming a `Sequence` in order to remove all the duplicate values it contains is a classic use case. To implement it, one could be tempted to transform the `Sequence` into a `Set`, then back to an `Array`. The downside with this approach is that it will not preserve the order of the sequence, which can definitely be a dealbreaker. Using `reduce()` it is possible to provide a concise implementation that preserves ordering: 1150 | 1151 | ```swift 1152 | import Foundation 1153 | 1154 | extension Sequence where Element: Equatable { 1155 | func duplicatesRemoved() -> [Element] { 1156 | return reduce([], { $0.contains($1) ? $0 : $0 + [$1] }) 1157 | } 1158 | } 1159 | 1160 | let data = [2, 5, 2, 3, 6, 5, 2] 1161 | 1162 | data.duplicatesRemoved() // [2, 5, 3, 6] 1163 | ``` 1164 | 1165 | ## Shorter syntax to deal with optional strings 1166 | 1167 | Optional strings are very common in Swift code, for instance many objects from `UIKit` expose the text they display as a `String?`. Many times you will need to manipulate this data as an unwrapped `String`, with a default value set to the empty string for `nil` cases. 1168 | 1169 | While the nil-coalescing operator (e.g. `??`) is a perfectly fine way to a achieve this goal, defining a computed variable like `orEmpty` can help a lot in cleaning the syntax. 1170 | 1171 | ```swift 1172 | import Foundation 1173 | import UIKit 1174 | 1175 | extension Optional where Wrapped == String { 1176 | var orEmpty: String { 1177 | switch self { 1178 | case .some(let value): 1179 | return value 1180 | case .none: 1181 | return "" 1182 | } 1183 | } 1184 | } 1185 | 1186 | func doesNotWorkWithOptionalString(_ param: String) { 1187 | // do something with `param` 1188 | } 1189 | 1190 | let label = UILabel() 1191 | label.text = "This is some text." 1192 | 1193 | doesNotWorkWithOptionalString(label.text.orEmpty) 1194 | ``` 1195 | 1196 | [![](https://img.youtube.com/vi/0lwxysw22GA/0.jpg)](https://www.youtube.com/watch?v=0lwxysw22GA) 1197 | 1198 | ## Encapsulating background computation and UI update 1199 | 1200 | Every seasoned iOS developers knows it: objects from `UIKit` can only be accessed from the main thread. Any attempt to access them from a background thread is a guaranteed crash. 1201 | 1202 | Still, running a costly computation on the background, and then using it to update the UI can be a common pattern. 1203 | 1204 | In such cases you can rely on `asyncUI` to encapsulate all the boilerplate code. 1205 | 1206 | ```swift 1207 | import Foundation 1208 | import UIKit 1209 | 1210 | func asyncUI(_ computation: @autoclosure @escaping () -> T, qos: DispatchQoS.QoSClass = .userInitiated, _ completion: @escaping (T) -> Void) { 1211 | DispatchQueue.global(qos: qos).async { 1212 | let value = computation() 1213 | DispatchQueue.main.async { 1214 | completion(value) 1215 | } 1216 | } 1217 | } 1218 | 1219 | let label = UILabel() 1220 | 1221 | func costlyComputation() -> Int { return (0..<10_000).reduce(0, +) } 1222 | 1223 | asyncUI(costlyComputation()) { value in 1224 | label.text = "\(value)" 1225 | } 1226 | ``` 1227 | 1228 | ## Retrieving all the necessary data to build a debug view 1229 | 1230 | A debug view, from which any controller of an app can be instantiated and pushed on the navigation stack, has the potential to bring some real value to a development process. A requirement to build such a view is to have a list of all the classes from a given `Bundle` that inherit from `UIViewController`. With the following `extension`, retrieving this list becomes a piece of cake 🍰 1231 | 1232 | ```swift 1233 | import Foundation 1234 | import UIKit 1235 | import ObjectiveC 1236 | 1237 | extension Bundle { 1238 | func viewControllerTypes() -> [UIViewController.Type] { 1239 | guard let bundlePath = self.executablePath else { return [] } 1240 | 1241 | var size: UInt32 = 0 1242 | var rawClassNames: UnsafeMutablePointer>! 1243 | var parsedClassNames = [String]() 1244 | 1245 | rawClassNames = objc_copyClassNamesForImage(bundlePath, &size) 1246 | 1247 | for index in 0.. I share the credit for this tip with [Benoît Caron](https://www.linkedin.com/in/benoît-caron-57530634/). 1267 | 1268 | ## Defining a function to map over dictionaries 1269 | 1270 | **Update** As it turns out, `map` is actually a really bad name for this function, because it does not preserve composition of transformations, a property that is required to fit the [definition](https://en.wikipedia.org/wiki/Functor) of a real `map` function. 1271 | 1272 | Surprisingly enough, the standard library doesn't define a `map()` function for dictionaries that allows to map both `keys` and `values` into a new `Dictionary`. Nevertheless, such a function can be helpful, for instance when converting data across different frameworks. 1273 | 1274 | ```swift 1275 | import Foundation 1276 | 1277 | extension Dictionary { 1278 | func map(_ transform: (Key, Value) throws -> (T, U)) rethrows -> [T: U] { 1279 | var result: [T: U] = [:] 1280 | 1281 | for (key, value) in self { 1282 | let (transformedKey, transformedValue) = try transform(key, value) 1283 | result[transformedKey] = transformedValue 1284 | } 1285 | 1286 | return result 1287 | } 1288 | } 1289 | 1290 | let data = [0: 5, 1: 6, 2: 7] 1291 | data.map { ("\($0)", $1 * $1) } // ["2": 49, "0": 25, "1": 36] 1292 | ``` 1293 | 1294 | ## A shorter syntax to remove `nil` values 1295 | 1296 | Swift provides the function `compactMap()`, that can be used to remove `nil` values from a `Sequence` of optionals when calling it with an argument that just returns its parameter (i.e. `compactMap { $0 }`). Still, for such use cases it would be nice to get rid of the trailing closure. 1297 | 1298 | The implementation isn't as straightforward as your usual `extension`, but once it has been written, the call site definitely gets cleaner 👌 1299 | 1300 | ```swift 1301 | import Foundation 1302 | 1303 | protocol OptionalConvertible { 1304 | associatedtype Wrapped 1305 | func asOptional() -> Wrapped? 1306 | } 1307 | 1308 | extension Optional: OptionalConvertible { 1309 | func asOptional() -> Wrapped? { 1310 | return self 1311 | } 1312 | } 1313 | 1314 | extension Sequence where Element: OptionalConvertible { 1315 | func compacted() -> [Element.Wrapped] { 1316 | return compactMap { $0.asOptional() } 1317 | } 1318 | } 1319 | 1320 | let data = [nil, 1, 2, nil, 3, 5, nil, 8, nil] 1321 | data.compacted() // [1, 2, 3, 5, 8] 1322 | ``` 1323 | 1324 | ## Dealing with expirable values 1325 | 1326 | It might happen that your code has to deal with values that come with an expiration date. In a game, it could be a score multiplier that will only last for 30 seconds. Or it could be an authentication token for an API, with a 15 minutes lifespan. In both instances you can rely on the type `Expirable` to encapsulate the expiration logic. 1327 | 1328 | ```swift 1329 | import Foundation 1330 | 1331 | struct Expirable { 1332 | private var innerValue: T 1333 | private(set) var expirationDate: Date 1334 | 1335 | var value: T? { 1336 | return hasExpired() ? nil : innerValue 1337 | } 1338 | 1339 | init(value: T, expirationDate: Date) { 1340 | self.innerValue = value 1341 | self.expirationDate = expirationDate 1342 | } 1343 | 1344 | init(value: T, duration: Double) { 1345 | self.innerValue = value 1346 | self.expirationDate = Date().addingTimeInterval(duration) 1347 | } 1348 | 1349 | func hasExpired() -> Bool { 1350 | return expirationDate < Date() 1351 | } 1352 | } 1353 | 1354 | let expirable = Expirable(value: 42, duration: 3) 1355 | 1356 | sleep(2) 1357 | expirable.value // 42 1358 | sleep(2) 1359 | expirable.value // nil 1360 | ``` 1361 | 1362 | > I share the credit for this tip with [Benoît Caron](https://www.linkedin.com/in/benoît-caron-57530634/). 1363 | 1364 | ## Using parallelism to speed-up `map()` 1365 | 1366 | Almost all Apple devices able to run Swift code are powered by a multi-core CPU, consequently making a good use of parallelism is a great way to improve code performance. `map()` is a perfect candidate for such an optimization, because it is almost trivial to define a parallel implementation. 1367 | 1368 | 1369 | ```swift 1370 | import Foundation 1371 | 1372 | extension Array { 1373 | func parallelMap(_ transform: (Element) -> T) -> [T] { 1374 | let res = UnsafeMutablePointer.allocate(capacity: count) 1375 | 1376 | DispatchQueue.concurrentPerform(iterations: count) { i in 1377 | res[i] = transform(self[i]) 1378 | } 1379 | 1380 | let finalResult = Array(UnsafeBufferPointer(start: res, count: count)) 1381 | res.deallocate(capacity: count) 1382 | 1383 | return finalResult 1384 | } 1385 | } 1386 | 1387 | let array = (0..<1_000).map { $0 } 1388 | 1389 | func work(_ n: Int) -> Int { 1390 | return (0.. Void) { 1406 | let start = Date() 1407 | for _ in 0..(_ left: @autoclosure () -> T, _ right: @autoclosure () -> U) -> (T, U) { 1429 | var leftRes: T? 1430 | var rightRes: U? 1431 | 1432 | DispatchQueue.concurrentPerform(iterations: 2, execute: { id in 1433 | if id == 0 { 1434 | leftRes = left() 1435 | } else { 1436 | rightRes = right() 1437 | } 1438 | }) 1439 | 1440 | return (leftRes!, rightRes!) 1441 | } 1442 | 1443 | let values = (1...100_000).map { $0 } 1444 | 1445 | let results = parallel(values.map { $0 * $0 }, values.reduce(0, +)) 1446 | ``` 1447 | 1448 | ## Making good use of \#file, \#line and \#function 1449 | 1450 | Swift exposes three special variables `#file`, `#line` and `#function`, that are respectively set to the name of the current file, line and function. Those variables become very useful when writing custom logging functions or test predicates. 1451 | 1452 | ```swift 1453 | import Foundation 1454 | 1455 | func log(_ message: String, _ file: String = #file, _ line: Int = #line, _ function: String = #function) { 1456 | print("[\(file):\(line)] \(function) - \(message)") 1457 | } 1458 | 1459 | func foo() { 1460 | log("Hello world!") 1461 | } 1462 | 1463 | foo() // [MyPlayground.playground:8] foo() - Hello world! 1464 | ``` 1465 | 1466 | [![](https://img.youtube.com/vi/KhZSmY2CqBk/0.jpg)](https://www.youtube.com/watch?v=KhZSmY2CqBk) 1467 | 1468 | ## Comparing Optionals through Conditional Conformance 1469 | 1470 | 1471 | Swift 4.1 has introduced a new feature called [Conditional Conformance](https://swift.org/blog/conditional-conformance/), which allows a type to implement a protocol only when its generic type also does. 1472 | 1473 | With this addition it becomes easy to let `Optional` implement `Comparable` only when `Wrapped` also implements `Comparable`: 1474 | 1475 | ```swift 1476 | import Foundation 1477 | 1478 | extension Optional: Comparable where Wrapped: Comparable { 1479 | public static func < (lhs: Optional, rhs: Optional) -> Bool { 1480 | switch (lhs, rhs) { 1481 | case let (lhs?, rhs?): 1482 | return lhs < rhs 1483 | case (nil, _?): 1484 | return true // anything is greater than nil 1485 | case (_?, nil): 1486 | return false // nil in smaller than anything 1487 | case (nil, nil): 1488 | return true // nil is not smaller than itself 1489 | } 1490 | } 1491 | } 1492 | 1493 | let data: [Int?] = [8, 4, 3, nil, 12, 4, 2, nil, -5] 1494 | data.sorted() // [nil, nil, Optional(-5), Optional(2), Optional(3), Optional(4), Optional(4), Optional(8), Optional(12)] 1495 | ``` 1496 | 1497 | ## Safely subscripting a Collection 1498 | 1499 | Any attempt to access an `Array` beyond its bounds will result in a crash. While it's possible to write conditions such as `if index < array.count { array[index] }` in order to prevent such crashes, this approach will rapidly become cumbersome. 1500 | 1501 | A great thing is that this condition can be encapsulated in a custom `subscript` that will work on any `Collection`: 1502 | 1503 | ```swift 1504 | import Foundation 1505 | 1506 | extension Collection { 1507 | subscript (safe index: Index) -> Element? { 1508 | return indices.contains(index) ? self[index] : nil 1509 | } 1510 | } 1511 | 1512 | let data = [1, 3, 4] 1513 | 1514 | data[safe: 1] // Optional(3) 1515 | data[safe: 10] // nil 1516 | ``` 1517 | 1518 | [![](https://img.youtube.com/vi/wps0HYAbUK0/0.jpg)](https://www.youtube.com/watch?v=wps0HYAbUK0) 1519 | 1520 | ## Easier String slicing using ranges 1521 | 1522 | Subscripting a string with a range can be very cumbersome in Swift 4. Let's face it, no one wants to write lines like `someString[index(startIndex, offsetBy: 0)..) -> Substring { 1531 | get { 1532 | return self[index(startIndex, offsetBy: value.lowerBound)...index(startIndex, offsetBy: value.upperBound)] 1533 | } 1534 | } 1535 | 1536 | public subscript(value: CountableRange) -> Substring { 1537 | get { 1538 | return self[index(startIndex, offsetBy: value.lowerBound)..) -> Substring { 1543 | get { 1544 | return self[..) -> Substring { 1549 | get { 1550 | return self[...index(startIndex, offsetBy: value.upperBound)] 1551 | } 1552 | } 1553 | 1554 | public subscript(value: PartialRangeFrom) -> Substring { 1555 | get { 1556 | return self[index(startIndex, offsetBy: value.lowerBound)...] 1557 | } 1558 | } 1559 | } 1560 | 1561 | let data = "This is a string!" 1562 | 1563 | data[..<4] // "This" 1564 | data[5..<9] // "is a" 1565 | data[10...] // "string!" 1566 | ``` 1567 | 1568 | ## Concise syntax for sorting using a KeyPath 1569 | 1570 | By using a `KeyPath` along with a generic type, a very clean and concise syntax for sorting data can be implemented: 1571 | 1572 | ```swift 1573 | import Foundation 1574 | 1575 | extension Sequence { 1576 | func sorted(by attribute: KeyPath) -> [Element] { 1577 | return sorted(by: { $0[keyPath: attribute] < $1[keyPath: attribute] }) 1578 | } 1579 | } 1580 | 1581 | let data = ["Some", "words", "of", "different", "lengths"] 1582 | 1583 | data.sorted(by: \.count) // ["of", "Some", "words", "lengths", "different"] 1584 | ``` 1585 | 1586 | If you like this syntax, make sure to checkout [KeyPathKit](https://github.com/vincent-pradeilles/KeyPathKit)! 1587 | 1588 | ## Manufacturing cache-efficient versions of pure functions 1589 | 1590 | By capturing a local variable in a returned closure, it is possible to manufacture cache-efficient versions of [pure functions](https://en.wikipedia.org/wiki/Pure_function). Be careful though, this trick only works with non-recursive function! 1591 | 1592 | ```swift 1593 | import Foundation 1594 | 1595 | func cached(_ f: @escaping (In) -> Out) -> (In) -> Out { 1596 | var cache = [In: Out]() 1597 | 1598 | return { (input: In) -> Out in 1599 | if let cachedValue = cache[input] { 1600 | return cachedValue 1601 | } else { 1602 | let result = f(input) 1603 | cache[input] = result 1604 | return result 1605 | } 1606 | } 1607 | } 1608 | 1609 | let cachedCos = cached { (x: Double) in cos(x) } 1610 | 1611 | cachedCos(.pi * 2) // value of cos for 2π is now cached 1612 | ``` 1613 | 1614 | ## Simplifying complex conditions with pattern matching 1615 | 1616 | When distinguishing between complex boolean conditions, using a `switch` statement along with pattern matching can be more readable than the classic series of `if {} else if {}`. 1617 | 1618 | ```swift 1619 | import Foundation 1620 | 1621 | let expr1: Bool 1622 | let expr2: Bool 1623 | let expr3: Bool 1624 | 1625 | if expr1 && !expr3 { 1626 | functionA() 1627 | } else if !expr2 && expr3 { 1628 | functionB() 1629 | } else if expr1 && !expr2 && expr3 { 1630 | functionC() 1631 | } 1632 | 1633 | switch (expr1, expr2, expr3) { 1634 | 1635 | case (true, _, false): 1636 | functionA() 1637 | case (_, false, true): 1638 | functionB() 1639 | case (true, false, true): 1640 | functionC() 1641 | default: 1642 | break 1643 | } 1644 | ``` 1645 | 1646 | ## Easily generating arrays of data 1647 | 1648 | Using `map()` on a range makes it easy to generate an array of data. 1649 | 1650 | ```swift 1651 | import Foundation 1652 | 1653 | func randomInt() -> Int { return Int(arc4random()) } 1654 | 1655 | let randomArray = (1...10).map { _ in randomInt() } 1656 | ``` 1657 | 1658 | ## Using @autoclosure for cleaner call sites 1659 | 1660 | Using `@autoclosure` enables the compiler to automatically wrap an argument within a closure, thus allowing for a very clean syntax at call sites. 1661 | 1662 | ```swift 1663 | import UIKit 1664 | 1665 | extension UIView { 1666 | class func animate(withDuration duration: TimeInterval, _ animations: @escaping @autoclosure () -> Void) { 1667 | UIView.animate(withDuration: duration, animations: animations) 1668 | } 1669 | } 1670 | 1671 | let view = UIView() 1672 | 1673 | UIView.animate(withDuration: 0.3, view.backgroundColor = .orange) 1674 | ``` 1675 | 1676 | ## Observing new and old value with RxSwift 1677 | 1678 | When working with RxSwift, it's very easy to observe both the current and previous value of an observable sequence by simply introducing a shift using `skip()`. 1679 | 1680 | ```swift 1681 | import RxSwift 1682 | 1683 | let values = Observable.of(4, 8, 15, 16, 23, 42) 1684 | 1685 | let newAndOld = Observable.zip(values, values.skip(1)) { (previous: $0, current: $1) } 1686 | .subscribe(onNext: { pair in 1687 | print("current: \(pair.current) - previous: \(pair.previous)") 1688 | }) 1689 | 1690 | //current: 8 - previous: 4 1691 | //current: 15 - previous: 8 1692 | //current: 16 - previous: 15 1693 | //current: 23 - previous: 16 1694 | //current: 42 - previous: 23 1695 | ``` 1696 | 1697 | ## Implicit initialization from literal values 1698 | 1699 | Using protocols such as `ExpressibleByStringLiteral` it is possible to provide an `init` that will be automatically when a literal value is provided, allowing for nice and short syntax. This can be very helpful when writing mock or test data. 1700 | 1701 | ```swift 1702 | import Foundation 1703 | 1704 | extension URL: ExpressibleByStringLiteral { 1705 | public init(stringLiteral value: String) { 1706 | self.init(string: value)! 1707 | } 1708 | } 1709 | 1710 | let url: URL = "http://www.google.fr" 1711 | 1712 | NSURLConnection.canHandle(URLRequest(url: "http://www.google.fr")) 1713 | ``` 1714 | 1715 | [![](https://img.youtube.com/vi/RG4YXbQXhxY/0.jpg)](https://www.youtube.com/watch?v=RG4YXbQXhxY) 1716 | 1717 | ## Achieving systematic validation of data 1718 | 1719 | Through some clever use of Swift `private` visibility it is possible to define a container that holds any untrusted value (such as a user input) from which the only way to retrieve the value is by making it successfully pass a validation test. 1720 | 1721 | ```swift 1722 | import Foundation 1723 | 1724 | struct Untrusted { 1725 | private(set) var value: T 1726 | } 1727 | 1728 | protocol Validator { 1729 | associatedtype T 1730 | static func validation(value: T) -> Bool 1731 | } 1732 | 1733 | extension Validator { 1734 | static func validate(untrusted: Untrusted) -> T? { 1735 | if self.validation(value: untrusted.value) { 1736 | return untrusted.value 1737 | } else { 1738 | return nil 1739 | } 1740 | } 1741 | } 1742 | 1743 | struct FrenchPhoneNumberValidator: Validator { 1744 | static func validation(value: String) -> Bool { 1745 | return (value.count) == 10 && CharacterSet(charactersIn: value).isSubset(of: CharacterSet.decimalDigits) 1746 | } 1747 | } 1748 | 1749 | let validInput = Untrusted(value: "0122334455") 1750 | let invalidInput = Untrusted(value: "0123") 1751 | 1752 | FrenchPhoneNumberValidator.validate(untrusted: validInput) // returns "0122334455" 1753 | FrenchPhoneNumberValidator.validate(untrusted: invalidInput) // returns nil 1754 | ``` 1755 | 1756 | ## Implementing the builder pattern with keypaths 1757 | 1758 | With the addition of keypaths in Swift 4, it is now possible to easily implement the builder pattern, that allows the developer to clearly separate the code that initializes a value from the code that uses it, without the burden of defining a factory method. 1759 | 1760 | ```swift 1761 | import UIKit 1762 | 1763 | protocol With {} 1764 | 1765 | extension With where Self: AnyObject { 1766 | @discardableResult 1767 | func with(_ property: ReferenceWritableKeyPath, setTo value: T) -> Self { 1768 | self[keyPath: property] = value 1769 | return self 1770 | } 1771 | } 1772 | 1773 | extension UIView: With {} 1774 | 1775 | let view = UIView() 1776 | 1777 | let label = UILabel() 1778 | .with(\.textColor, setTo: .red) 1779 | .with(\.text, setTo: "Foo") 1780 | .with(\.textAlignment, setTo: .right) 1781 | .with(\.layer.cornerRadius, setTo: 5) 1782 | 1783 | view.addSubview(label) 1784 | ``` 1785 | 1786 | 🚨 The Swift compiler **does not** perform OS availability checks on properties referenced by keypaths. Any attempt to use a `KeyPath` for an unavailable property will result in a runtime crash. 1787 | 1788 | > I share the credit for this tip with [Marion Curtil](https://www.linkedin.com/in/marion-curtil-1a478970/). 1789 | 1790 | ## Storing functions rather than values 1791 | 1792 | When a type stores values for the sole purpose of parametrizing its functions, it’s then possible to not store the values but directly the function, with no discernable difference at the call site. 1793 | 1794 | ```swift 1795 | import Foundation 1796 | 1797 | struct MaxValidator { 1798 | let max: Int 1799 | let strictComparison: Bool 1800 | 1801 | func isValid(_ value: Int) -> Bool { 1802 | return self.strictComparison ? value < self.max : value <= self.max 1803 | } 1804 | } 1805 | 1806 | struct MaxValidator2 { 1807 | var isValid: (_ value: Int) -> Bool 1808 | 1809 | init(max: Int, strictComparison: Bool) { 1810 | self.isValid = strictComparison ? { $0 < max } : { $0 <= max } 1811 | } 1812 | } 1813 | 1814 | MaxValidator(max: 5, strictComparison: true).isValid(5) // false 1815 | MaxValidator2(max: 5, strictComparison: false).isValid(5) // true 1816 | ``` 1817 | 1818 | ## Defining operators on function types 1819 | 1820 | Functions are first-class citizen types in Swift, so it is perfectly legal to define operators for them. 1821 | 1822 | ```swift 1823 | import Foundation 1824 | 1825 | let firstRange = { (0...3).contains($0) } 1826 | let secondRange = { (5...6).contains($0) } 1827 | 1828 | func ||(_ lhs: @escaping (Int) -> Bool, _ rhs: @escaping (Int) -> Bool) -> (Int) -> Bool { 1829 | return { value in 1830 | return lhs(value) || rhs(value) 1831 | } 1832 | } 1833 | 1834 | (firstRange || secondRange)(2) // true 1835 | (firstRange || secondRange)(4) // false 1836 | (firstRange || secondRange)(6) // true 1837 | ``` 1838 | 1839 | ## Typealiases for functions 1840 | 1841 | Typealiases are great to express function signatures in a more comprehensive manner, which then enables us to easily define functions that operate on them, resulting in a nice way to write and use some powerful API. 1842 | 1843 | ```swift 1844 | import Foundation 1845 | 1846 | typealias RangeSet = (Int) -> Bool 1847 | 1848 | func union(_ left: @escaping RangeSet, _ right: @escaping RangeSet) -> RangeSet { 1849 | return { left($0) || right($0) } 1850 | } 1851 | 1852 | let firstRange = { (0...3).contains($0) } 1853 | let secondRange = { (5...6).contains($0) } 1854 | 1855 | let unionRange = union(firstRange, secondRange) 1856 | 1857 | unionRange(2) // true 1858 | unionRange(4) // false 1859 | ``` 1860 | 1861 | ## Encapsulating state within a function 1862 | 1863 | By returning a closure that captures a local variable, it's possible to encapsulate a mutable state within a function. 1864 | 1865 | ```swift 1866 | import Foundation 1867 | 1868 | func counterFactory() -> () -> Int { 1869 | var counter = 0 1870 | 1871 | return { 1872 | counter += 1 1873 | return counter 1874 | } 1875 | } 1876 | 1877 | let counter = counterFactory() 1878 | 1879 | counter() // returns 1 1880 | counter() // returns 2 1881 | ``` 1882 | 1883 | ## Generating all cases for an Enum 1884 | 1885 | > ⚠️ Since Swift 4.2, `allCases` can now be synthesized at compile-time by simply conforming to the protocol `CaseIterable`. The implementation below should no longer be used in production code. 1886 | 1887 | Through some clever leveraging of how enums are stored in memory, it is possible to generate an array that contains all the possible cases of an enum. This can prove particularly useful when writing unit tests that consume random data. 1888 | 1889 | ```swift 1890 | import Foundation 1891 | 1892 | enum MyEnum { case first; case second; case third; case fourth } 1893 | 1894 | protocol EnumCollection: Hashable { 1895 | static var allCases: [Self] { get } 1896 | } 1897 | 1898 | extension EnumCollection { 1899 | public static var allCases: [Self] { 1900 | var i = 0 1901 | return Array(AnyIterator { 1902 | let next = withUnsafePointer(to: &i) { 1903 | $0.withMemoryRebound(to: Self.self, capacity: 1) { $0.pointee } 1904 | } 1905 | if next.hashValue != i { return nil } 1906 | i += 1 1907 | return next 1908 | }) 1909 | } 1910 | } 1911 | 1912 | extension MyEnum: EnumCollection { } 1913 | 1914 | MyEnum.allCases // [.first, .second, .third, .fourth] 1915 | ``` 1916 | 1917 | ## Using map on optional values 1918 | 1919 | The if-let syntax is a great way to deal with optional values in a safe manner, but at times it can prove to be just a little bit to cumbersome. In such cases, using the `Optional.map()` function is a nice way to achieve a shorter code while retaining safeness and readability. 1920 | 1921 | 1922 | ```swift 1923 | import UIKit 1924 | 1925 | let date: Date? = Date() // or could be nil, doesn't matter 1926 | let formatter = DateFormatter() 1927 | let label = UILabel() 1928 | 1929 | if let safeDate = date { 1930 | label.text = formatter.string(from: safeDate) 1931 | } 1932 | 1933 | label.text = date.map { return formatter.string(from: $0) } 1934 | 1935 | label.text = date.map(formatter.string(from:)) // even shorter, tough less readable 1936 | ``` 1937 | 1938 | [![](https://img.youtube.com/vi/vnsKOxOrXnY/0.jpg)](https://www.youtube.com/watch?v=vnsKOxOrXnY) 1939 | -------------------------------------------------------------------------------- /SwiftTips.playground/Pages/01 - Using map on optional values.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | //: [Previous](@previous) 2 | 3 | import UIKit 4 | 5 | /* 6 | The if-let syntax is a great way to deal with optional values in a safe manner, but at 7 | times it can prove to be just a little bit to cumbersome. In such cases, using the 8 | `Optional.map()` function is a nice way to achieve a shorter code while retaining safeness 9 | and readability. 10 | */ 11 | 12 | let date: Date? = Date() // or could be nil, doesn't matter 13 | let formatter = DateFormatter() 14 | let label = UILabel() 15 | 16 | if let safeDate = date { 17 | label.text = formatter.string(from: safeDate) 18 | } 19 | 20 | label.text = date.map { return formatter.string(from: $0) } 21 | 22 | label.text = date.map(formatter.string(from:)) // even shorter, tough less readable 23 | 24 | //: [Next](@next) 25 | -------------------------------------------------------------------------------- /SwiftTips.playground/Pages/02 - Generating all cases for an Enum.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | //: [Previous](@previous) 2 | 3 | /* 4 | Through some clever leveraging of how enums are stored in memory, it is possible 5 | to generate an array that contains all the possible cases of an enum. This can 6 | prove particularly useful when writing unit tests that consume random data. 7 | */ 8 | 9 | import Foundation 10 | 11 | enum MyEnum { case first; case second; case third; case fourth } 12 | 13 | protocol EnumCollection: Hashable { 14 | static var allCases: [Self] { get } 15 | } 16 | 17 | extension EnumCollection { 18 | public static var allCases: [Self] { 19 | var i = 0 20 | return Array(AnyIterator { 21 | let next = withUnsafePointer(to: &i) { 22 | $0.withMemoryRebound(to: Self.self, capacity: 1) { $0.pointee } 23 | } 24 | if next.hashValue != i { return nil } 25 | i += 1 26 | return next 27 | }) 28 | } 29 | } 30 | 31 | extension MyEnum: EnumCollection { } 32 | 33 | MyEnum.allCases // [.first, .second, .third, .fourth] 34 | 35 | //: [Next](@next) 36 | -------------------------------------------------------------------------------- /SwiftTips.playground/Pages/03 - Encapsulating state within a function.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | //: [Previous](@previous) 2 | 3 | /* 4 | By returning a closure that captures a local variable, it's possible to 5 | encapsulate a mutable state within a function. 6 | */ 7 | 8 | import Foundation 9 | 10 | func counterFactory() -> () -> Int { 11 | var counter = 0 12 | 13 | return { 14 | counter += 1 15 | return counter 16 | } 17 | } 18 | 19 | let counter = counterFactory() 20 | 21 | counter() // returns 1 22 | counter() // returns 2 23 | 24 | //: [Next](@next) 25 | -------------------------------------------------------------------------------- /SwiftTips.playground/Pages/04 - Typealiases for functions.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | //: [Previous](@previous) 2 | 3 | /* 4 | Typealiases are great to express function signatures in a more 5 | comprehensive manner, which then enables us to easily define functions 6 | that operate on them, resulting in a nice way to write and use some 7 | powerful API. 8 | */ 9 | 10 | import Foundation 11 | 12 | typealias RangeSet = (Int) -> Bool 13 | 14 | func union(_ left: @escaping RangeSet, _ right: @escaping RangeSet) -> RangeSet { 15 | return { left($0) || right($0) } 16 | } 17 | 18 | let firstRange = { (0...3).contains($0) } 19 | let secondRange = { (5...6).contains($0) } 20 | 21 | let unionRange = union(firstRange, secondRange) 22 | 23 | unionRange(2) // true 24 | unionRange(4) // false 25 | 26 | //: [Next](@next) 27 | -------------------------------------------------------------------------------- /SwiftTips.playground/Pages/05 - Defining operators on function types.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | //: [Previous](@previous) 2 | 3 | /* 4 | Functions are first-class citizen types in Swift, so it is 5 | perfectly legal to define operators for them. 6 | */ 7 | 8 | import Foundation 9 | 10 | let firstRange = { (0...3).contains($0) } 11 | let secondRange = { (5...6).contains($0) } 12 | 13 | func ||(_ lhs: @escaping (Int) -> Bool, _ rhs: @escaping (Int) -> Bool) -> (Int) -> Bool { 14 | return { value in 15 | return lhs(value) || rhs(value) 16 | } 17 | } 18 | 19 | (firstRange || secondRange)(2) // true 20 | (firstRange || secondRange)(4) // false 21 | (firstRange || secondRange)(6) // true 22 | 23 | //: [Next](@next) 24 | -------------------------------------------------------------------------------- /SwiftTips.playground/Pages/06 - Storing functions rather than values.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | //: [Previous](@previous) 2 | 3 | /* 4 | When a type stores values for the sole purpose of parametrizing 5 | its functions, it’s then possible to not store the values but 6 | directly the function, with no discernable difference at the call site. 7 | */ 8 | import Foundation 9 | 10 | struct MaxValidator { 11 | let max: Int 12 | let strictComparison: Bool 13 | 14 | func isValid(_ value: Int) -> Bool { 15 | return self.strictComparison ? value < self.max : value <= self.max 16 | } 17 | } 18 | 19 | struct MaxValidator2 { 20 | var isValid: (_ value: Int) -> Bool 21 | 22 | init(max: Int, strictComparison: Bool) { 23 | self.isValid = strictComparison ? { $0 < max } : { $0 <= max } 24 | } 25 | } 26 | 27 | MaxValidator(max: 5, strictComparison: true).isValid(5) // false 28 | MaxValidator2(max: 5, strictComparison: false).isValid(5) // true 29 | 30 | //: [Next](@next) 31 | -------------------------------------------------------------------------------- /SwiftTips.playground/Pages/07 - Implementing the builder pattern with keypaths.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | //: [Previous](@previous) 2 | 3 | /* 4 | With the addition of keypaths in Swift 4, it is now possible 5 | to easily implement the builder pattern, that allows the 6 | developer to clearly separate the code that initializes a value 7 | from the code that uses it, without the burden of defining a 8 | factory method. 9 | 10 | 🚨 The Swift compiler **does not** perform OS availability checks 11 | on properties referenced by keypaths. Any attempt to use a `KeyPath` 12 | for an unavailable property will result in a runtime crash. 13 | */ 14 | 15 | import UIKit 16 | 17 | protocol With {} 18 | 19 | extension With where Self: AnyObject { 20 | @discardableResult 21 | func with(_ property: ReferenceWritableKeyPath, setTo value: T) -> Self { 22 | self[keyPath: property] = value 23 | return self 24 | } 25 | } 26 | 27 | extension UIView: With {} 28 | 29 | let view = UIView() 30 | 31 | let label = UILabel() 32 | .with(\.textColor, setTo: .red) 33 | .with(\.text, setTo: "Foo") 34 | .with(\.textAlignment, setTo: .right) 35 | .with(\.layer.cornerRadius, setTo: 5) 36 | 37 | view.addSubview(label) 38 | 39 | //: [Next](@next) 40 | -------------------------------------------------------------------------------- /SwiftTips.playground/Pages/08 - Achieving systematic validation of data.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | //: [Previous](@previous) 2 | 3 | /* 4 | Through some clever use of Swift `private` visibility 5 | it is possible to define a container that holds any 6 | untrusted value (such as a user input) from which the 7 | only way to retrieve the value is by making it successfully 8 | pass a validation test. 9 | */ 10 | 11 | import Foundation 12 | 13 | struct Untrusted { 14 | private(set) var value: T 15 | } 16 | 17 | protocol Validator { 18 | associatedtype T 19 | static func validation(value: T) -> Bool 20 | } 21 | 22 | extension Validator { 23 | static func validate(untrusted: Untrusted) -> T? { 24 | if self.validation(value: untrusted.value) { 25 | return untrusted.value 26 | } else { 27 | return nil 28 | } 29 | } 30 | } 31 | 32 | struct FrenchPhoneNumberValidator: Validator { 33 | static func validation(value: String) -> Bool { 34 | return (value.count) == 10 && CharacterSet(charactersIn: value).isSubset(of: CharacterSet.decimalDigits) 35 | } 36 | } 37 | 38 | let validInput = Untrusted(value: "0122334455") 39 | let invalidInput = Untrusted(value: "0123") 40 | 41 | FrenchPhoneNumberValidator.validate(untrusted: validInput) // returns "0122334455" 42 | FrenchPhoneNumberValidator.validate(untrusted: invalidInput) // returns nil 43 | 44 | //: [Next](@next) 45 | -------------------------------------------------------------------------------- /SwiftTips.playground/Pages/09 - Implicit initialization from literal values.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | //: [Previous](@previous) 2 | 3 | /* 4 | Using protocols such as `ExpressibleByStringLiteral` it 5 | is possible to provide an `init` that will be automatically 6 | when a literal value is provided, allowing for nice and short 7 | syntax. This can be very helpful when writing mock or test data. 8 | */ 9 | 10 | import Foundation 11 | 12 | extension URL: ExpressibleByStringLiteral { 13 | public init(stringLiteral value: String) { 14 | self.init(string: value)! 15 | } 16 | } 17 | 18 | let url: URL = "http://www.google.fr" 19 | 20 | NSURLConnection.canHandle(URLRequest(url: "http://www.google.fr")) 21 | 22 | //: [Next](@next) 23 | -------------------------------------------------------------------------------- /SwiftTips.playground/Pages/10 - Observing new and old value with RxSwift.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | //: [Previous](@previous) 2 | 3 | /* 4 | When working with RxSwift, it's very easy to observe 5 | both the current and previous value of an observable 6 | sequence by simply introducing a shift using `skip()`. 7 | */ 8 | 9 | import RxSwift 10 | 11 | let values = Observable.of(4, 8, 15, 16, 23, 42) 12 | 13 | let newAndOld = Observable.zip(values, values.skip(1)) { (previous: $0, current: $1) } 14 | .subscribe(onNext: { pair in 15 | print("current: \(pair.current) - previous: \(pair.previous)") 16 | }) 17 | 18 | //current: 8 - previous: 4 19 | //current: 15 - previous: 8 20 | //current: 16 - previous: 15 21 | //current: 23 - previous: 16 22 | //current: 42 - previous: 23 23 | 24 | //: [Next](@next) 25 | -------------------------------------------------------------------------------- /SwiftTips.playground/Pages/11 - Using @autoclosure for cleaner call sites.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | //: [Previous](@previous) 2 | 3 | /* 4 | Using `@autoclosure` enables the compiler to automatically 5 | wrap an argument within a closure, thus allowing for a very clean syntax at call sites. 6 | */ 7 | import UIKit 8 | 9 | extension UIView { 10 | class func animate(withDuration duration: TimeInterval, _ animations: @escaping @autoclosure () -> Void) { 11 | UIView.animate(withDuration: duration, animations: animations) 12 | } 13 | } 14 | 15 | let view = UIView() 16 | 17 | UIView.animate(withDuration: 0.3, view.backgroundColor = .orange) 18 | 19 | //: [Next](@next) 20 | -------------------------------------------------------------------------------- /SwiftTips.playground/Pages/12 - Easily generating arrays of data.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | //: [Previous](@previous) 2 | 3 | /* 4 | Using `map()` on a range makes it easy to generate 5 | an array of data. 6 | */ 7 | import Foundation 8 | 9 | func randomInt() -> Int { return Int(arc4random()) } 10 | 11 | let randomArray = (1...10).map { _ in randomInt() } 12 | 13 | //: [Next](@next) 14 | -------------------------------------------------------------------------------- /SwiftTips.playground/Pages/13 - Simplifying complex conditions with pattern matching.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | //: [Previous](@previous) 2 | 3 | /* 4 | When distinguishing between complex boolean conditions, 5 | using a `switch` statement along with pattern matching 6 | can be more readable than the classic series 7 | of `if {} else if {}`. 8 | */ 9 | 10 | import Foundation 11 | 12 | let expr1: Bool 13 | let expr2: Bool 14 | let expr3: Bool 15 | 16 | if expr1 && !expr3 { 17 | functionA() 18 | } else if !expr2 && expr3 { 19 | functionB() 20 | } else if expr1 && !expr2 && expr3 { 21 | functionC() 22 | } 23 | 24 | switch (expr1, expr2, expr3) { 25 | 26 | case (true, _, false): 27 | functionA() 28 | case (_, false, true): 29 | functionB() 30 | case (true, false, true): 31 | functionC() 32 | default: 33 | break 34 | } 35 | 36 | //: [Next](@next) 37 | -------------------------------------------------------------------------------- /SwiftTips.playground/Pages/14 - Manufacturing cache-efficient versions of pure functions.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | //: [Previous](@previous) 2 | 3 | /* 4 | By capturing a local variable in a returned closure, it is 5 | possible to manufacture cache-efficient versions of 6 | [pure functions](https://en.wikipedia.org/wiki/Pure_function). 7 | Be careful though, this trick only works with non-recursive function! 8 | */ 9 | import Foundation 10 | 11 | func cached(_ f: @escaping (In) -> Out) -> (In) -> Out { 12 | var cache = [In: Out]() 13 | 14 | return { (input: In) -> Out in 15 | if let cachedValue = cache[input] { 16 | return cachedValue 17 | } else { 18 | let result = f(input) 19 | cache[input] = result 20 | return result 21 | } 22 | } 23 | } 24 | 25 | let cachedCos = cached { (x: Double) in cos(x) } 26 | 27 | cachedCos(.pi * 2) // value of cos for 2π is now cached 28 | 29 | //: [Next](@next) 30 | -------------------------------------------------------------------------------- /SwiftTips.playground/Pages/15 - Concise syntax for sorting using a KeyPath.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | //: [Previous](@previous) 2 | 3 | /* 4 | By using a `KeyPath` along with a generic type, a very clean 5 | and concise syntax for sorting data can be implemented: 6 | */ 7 | 8 | import Foundation 9 | 10 | extension Sequence { 11 | func sorted(by attribute: KeyPath) -> [Element] { 12 | return sorted(by: { $0[keyPath: attribute] < $1[keyPath: attribute] }) 13 | } 14 | } 15 | 16 | let data = ["Some", "words", "of", "different", "lengths"] 17 | 18 | data.sorted(by: \.count) // ["of", "Some", "words", "lengths", "different"] 19 | 20 | //: [Next](@next) 21 | -------------------------------------------------------------------------------- /SwiftTips.playground/Pages/16 - Easier String slicing using ranges.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | //: [Previous](@previous) 2 | 3 | /* 4 | Subscripting a string with a range can be very cumbersome 5 | in Swift 4. Let's face it, no one wants to write lines like 6 | `someString[index(startIndex, offsetBy: 0)..) -> Substring { 16 | get { 17 | return self[index(startIndex, offsetBy: value.lowerBound)...index(startIndex, offsetBy: value.upperBound)] 18 | } 19 | } 20 | 21 | public subscript(value: CountableRange) -> Substring { 22 | get { 23 | return self[index(startIndex, offsetBy: value.lowerBound)..) -> Substring { 28 | get { 29 | return self[..) -> Substring { 34 | get { 35 | return self[...index(startIndex, offsetBy: value.upperBound)] 36 | } 37 | } 38 | 39 | public subscript(value: PartialRangeFrom) -> Substring { 40 | get { 41 | return self[index(startIndex, offsetBy: value.lowerBound)...] 42 | } 43 | } 44 | } 45 | 46 | let data = "This is a string!" 47 | 48 | data[..<4] // "This" 49 | data[5..<9] // "is a" 50 | data[10...] // "string!" 51 | 52 | //: [Next](@next) 53 | -------------------------------------------------------------------------------- /SwiftTips.playground/Pages/17 - Safely subscripting a Collection.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | //: [Previous](@previous) 2 | 3 | /* 4 | Any attempt to access an `Array` beyond its bounds will 5 | result in a crash. While it's possible to write conditions 6 | such as `if index < array.count { array[index] }` in order 7 | to prevent such crashes, this approach will rapidly become 8 | cumbersome. 9 | 10 | A great thing is that this condition can be encapsulated in 11 | a custom `subscript` that will work on any `Collection`: 12 | */ 13 | 14 | import Foundation 15 | 16 | extension Collection { 17 | subscript (safe index: Index) -> Element? { 18 | return indices.contains(index) ? self[index] : nil 19 | } 20 | } 21 | 22 | let data = [1, 3, 4] 23 | 24 | data[safe: 1] // Optional(3) 25 | data[safe: 10] // nil 26 | 27 | //: [Next](@next) 28 | -------------------------------------------------------------------------------- /SwiftTips.playground/Pages/18 - Comparing Optionals through Conditional Conformance.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | //: [Previous](@previous) 2 | 3 | /* 4 | Swift 4.1 has introduced a new feature called Conditional Conformance, 5 | which allows a type to implement a protocol only when its generic type also does. 6 | 7 | With this addition it becomes easy to let `Optional` implement `Comparable` 8 | only when `Wrapped` also implements `Comparable`: 9 | */ 10 | 11 | import Foundation 12 | 13 | extension Optional: Comparable where Wrapped: Comparable { 14 | public static func < (lhs: Optional, rhs: Optional) -> Bool { 15 | switch (lhs, rhs) { 16 | case let (lhs?, rhs?): 17 | return lhs < rhs 18 | case (nil, _?): 19 | return true // anything is greater than nil 20 | case (_?, nil): 21 | return false // nil in smaller than anything 22 | case (nil, nil): 23 | return true // nil is not smaller than itself 24 | } 25 | } 26 | } 27 | 28 | let data: [Int?] = [8, 4, 3, nil, 12, 4, 2, nil, -5] 29 | data.sorted() // [nil, nil, Optional(-5), Optional(2), Optional(3), Optional(4), Optional(4), Optional(8), Optional(12)] 30 | 31 | //: [Next](@next) 32 | -------------------------------------------------------------------------------- /SwiftTips.playground/Pages/19 - Making good use of #file, #line and #function.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | //: [Previous](@previous) 2 | 3 | /* 4 | Swift exposes three special variables called `#file`, `#line` and 5 | `#function`, that are respectively set to the name of the current file, 6 | line and function. Those variables become very useful when writing custom 7 | logging functions or test predicates. 8 | */ 9 | 10 | import Foundation 11 | 12 | func log(_ message: String, _ file: String = #file, _ line: Int = #line, _ function: String = #function) { 13 | print("[\(file):\(line)] \(function) - \(message)") 14 | } 15 | 16 | func foo() { 17 | log("Hello world!") 18 | } 19 | 20 | foo() // [SwiftTips.playground:17] foo() - Hello world! 21 | 22 | //: [Next](@next) 23 | -------------------------------------------------------------------------------- /SwiftTips.playground/Pages/20 - Running two pieces of code in parallel.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | //: [Previous](@previous) 2 | 3 | /* 4 | Concurrency is definitely one of those topics were the 5 | right encapsulation bears the potential to make your life 6 | so much easier. For instance, with this piece of code you 7 | can easily launch two computations in parallel, and have 8 | the results returned in a tuple. 9 | */ 10 | 11 | import Foundation 12 | 13 | func parallel(_ left: @autoclosure () -> T, _ right: @autoclosure () -> U) -> (T, U) { 14 | var leftRes: T? 15 | var rightRes: U? 16 | 17 | DispatchQueue.concurrentPerform(iterations: 2, execute: { id in 18 | if id == 0 { 19 | leftRes = left() 20 | } else { 21 | rightRes = right() 22 | } 23 | }) 24 | 25 | return (leftRes!, rightRes!) 26 | } 27 | 28 | let values = (1...100_000).map { $0 } 29 | 30 | let results = parallel(values.map { $0 * $0 }, values.reduce(0, +)) 31 | 32 | //: [Next](@next) 33 | -------------------------------------------------------------------------------- /SwiftTips.playground/Pages/21 - Measuring execution time with minimum boilerplate.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | //: [Previous](@previous) 2 | 3 | /* 4 | During development of a feature that performs some heavy 5 | computations, it can be helpful to measure just how much 6 | time a chunk of code takes to run. The `time()` function 7 | is a nice tool for this purpose, because of how simple it 8 | is to add and then to remove when it is no longer needed. 9 | */ 10 | 11 | import Foundation 12 | 13 | func time(averagedExecutions: Int = 1, _ code: () -> Void) { 14 | let start = Date() 15 | for _ in 0..(_ transform: (Element) -> T) -> [T] { 20 | let res = UnsafeMutablePointer.allocate(capacity: count) 21 | 22 | DispatchQueue.concurrentPerform(iterations: count) { i in 23 | res[i] = transform(self[i]) 24 | } 25 | 26 | let finalResult = Array(UnsafeBufferPointer(start: res, count: count)) 27 | res.deallocate(capacity: count) 28 | 29 | return finalResult 30 | } 31 | } 32 | 33 | let array = (0..<1_000).map { $0 } 34 | 35 | func work(_ n: Int) -> Int { 36 | return (0.. { 15 | private var innerValue: T 16 | private(set) var expirationDate: Date 17 | 18 | var value: T? { 19 | return hasExpired() ? nil : innerValue 20 | } 21 | 22 | init(value: T, expirationDate: Date) { 23 | self.innerValue = value 24 | self.expirationDate = expirationDate 25 | } 26 | 27 | init(value: T, duration: Double) { 28 | self.innerValue = value 29 | self.expirationDate = Date().addingTimeInterval(duration) 30 | } 31 | 32 | func hasExpired() -> Bool { 33 | return expirationDate < Date() 34 | } 35 | } 36 | 37 | let expirable = Expirable(value: 42, duration: 3) 38 | 39 | sleep(2) 40 | expirable.value // 42 41 | sleep(2) 42 | expirable.value // nil 43 | 44 | //: [Next](@next) 45 | -------------------------------------------------------------------------------- /SwiftTips.playground/Pages/24 - A shorter syntax to remove nil values.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | //: [Previous](@previous) 2 | 3 | /* 4 | Swift provides the function `compactMap()`, that can be used 5 | to remove `nil` values from a `Sequence` of optionals when calling it 6 | with an argument that just returns its parameter (i.e. `compactMap { $0 }`). 7 | Still, for such use cases it would be nice to get rid of the trailing closure. 8 | 9 | The implementation isn't as straightforward as your usual `extension`, 10 | but once it has been written, the call site definitely gets cleaner 👌 11 | */ 12 | 13 | import Foundation 14 | 15 | protocol OptionalConvertible { 16 | associatedtype Wrapped 17 | func asOptional() -> Wrapped? 18 | } 19 | 20 | extension Optional: OptionalConvertible { 21 | func asOptional() -> Wrapped? { 22 | return self 23 | } 24 | } 25 | 26 | extension Sequence where Element: OptionalConvertible { 27 | func compacted() -> [Element.Wrapped] { 28 | return compactMap { $0.asOptional() } 29 | } 30 | } 31 | 32 | let data = [nil, 1, 2, nil, 3, 5, nil, 8, nil] 33 | data.compacted() // [1, 2, 3, 5, 8] 34 | 35 | //: [Next](@next) 36 | -------------------------------------------------------------------------------- /SwiftTips.playground/Pages/25 - Defining a function to map over dictionaries.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | //: [Previous](@previous) 2 | 3 | /* 4 | Surprisingly enough, the standard library doesn't define a `map()` 5 | function for dictionaries that allows to map both `keys` and `values` 6 | into a new `Dictionary`. Nevertheless, such a function can be helpful, 7 | for instance when converting data across different frameworks. 8 | */ 9 | 10 | import Foundation 11 | 12 | extension Dictionary { 13 | func map(_ transform: (Key, Value) throws -> (T, U)) rethrows -> [T: U] { 14 | var result: [T: U] = [:] 15 | 16 | for (key, value) in self { 17 | let (transformedKey, transformedValue) = try transform(key, value) 18 | result[transformedKey] = transformedValue 19 | } 20 | 21 | return result 22 | } 23 | } 24 | 25 | let data = [0: 5, 1: 6, 2: 7] 26 | data.map { ("\($0)", $1 * $1) } // ["2": 49, "0": 25, "1": 36] 27 | 28 | //: [Next](@next) 29 | -------------------------------------------------------------------------------- /SwiftTips.playground/Pages/26 - Retrieving all the necessary data to build a debug view.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | //: [Previous](@previous) 2 | 3 | /* 4 | A debug view, from which any controller of an app can be 5 | instantiated and pushed on the navigation stack, has the 6 | potential to bring some real value to a development process. 7 | A requirement to build such a view is to have a list of all 8 | the classes from a given `Bundle` that inherit from 9 | `UIViewController`. 10 | With the following `extension`, retrieving 11 | this list becomes a piece of cake 🍰 12 | */ 13 | 14 | import Foundation 15 | import UIKit 16 | import ObjectiveC 17 | 18 | extension Bundle { 19 | func viewControllerTypes() -> [UIViewController.Type] { 20 | guard let bundlePath = self.executablePath else { return [] } 21 | 22 | var size: UInt32 = 0 23 | var rawClassNames: UnsafeMutablePointer>! 24 | var parsedClassNames = [String]() 25 | 26 | rawClassNames = objc_copyClassNamesForImage(bundlePath, &size) 27 | 28 | for index in 0..(_ computation: @autoclosure @escaping () -> T, qos: DispatchQoS.QoSClass = .userInitiated, _ completion: @escaping (T) -> Void) { 19 | DispatchQueue.global(qos: qos).async { 20 | let value = computation() 21 | DispatchQueue.main.async { 22 | completion(value) 23 | } 24 | } 25 | } 26 | 27 | let label = UILabel() 28 | 29 | func costlyComputation() -> Int { return (0..<10_000).reduce(0, +) } 30 | 31 | asyncUI(costlyComputation()) { value in 32 | label.text = "\(value)" 33 | } 34 | 35 | //: [Next](@next) 36 | -------------------------------------------------------------------------------- /SwiftTips.playground/Pages/28 - Shorter syntax to deal with optional strings.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | //: [Previous](@previous) 2 | 3 | /* 4 | Optional strings are very common in Swift code, for instance 5 | many objects from `UIKit` expose the text they display as a 6 | `String?`. Many times you will need to manipulate this data 7 | as an unwrapped `String`, with a default value set to the 8 | empty string for `nil` cases. 9 | 10 | While the nil-coalescing operator (e.g. `??`) is a perfectly 11 | fine way to a achieve this goal, defining a computed variable 12 | like `orEmpty` can help a lot in cleaning the syntax. 13 | */ 14 | 15 | import Foundation 16 | import UIKit 17 | 18 | extension Optional where Wrapped == String { 19 | var orEmpty: String { 20 | switch self { 21 | case .some(let value): 22 | return value 23 | case .none: 24 | return "" 25 | } 26 | } 27 | } 28 | 29 | func doesNotWorkWithOptionalString(_ param: String) { 30 | // do something with `param` 31 | } 32 | 33 | let label = UILabel() 34 | label.text = "This is some text." 35 | 36 | doesNotWorkWithOptionalString(label.text.orEmpty) 37 | 38 | //: [Next](@next) 39 | -------------------------------------------------------------------------------- /SwiftTips.playground/Pages/29 - Removing duplicate values from a Sequence.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | //: [Previous](@previous) 2 | 3 | /* 4 | Transforming a `Sequence` in order to remove all the duplicate 5 | values it contains is a classic use case. To implement it, one 6 | could be tempted to transform the `Sequence` into a `Set`, then 7 | back to an `Array`. The downside with this approach is that it 8 | will not preserve the order of the sequence, which can definitely 9 | be a dealbreaker. 10 | 11 | Using `reduce()` it is possible to provide a concise implementation 12 | that preserves ordering: 13 | */ 14 | 15 | import Foundation 16 | 17 | extension Sequence where Element: Equatable { 18 | func duplicatesRemoved() -> [Element] { 19 | return reduce([], { $0.contains($1) ? $0 : $0 + [$1] }) 20 | } 21 | } 22 | 23 | let data = [2, 5, 2, 3, 6, 5, 2] 24 | 25 | data.duplicatesRemoved() // [2, 5, 3, 6] 26 | 27 | //: [Next](@next) 28 | -------------------------------------------------------------------------------- /SwiftTips.playground/Pages/30 - Providing useful operators for Optional booleans.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | //: [Previous](@previous) 2 | 3 | /* 4 | When we need to apply the standard boolean operators to 5 | `Optional` booleans, we often end up with a syntax 6 | unnecessarily crowded with unwrapping operations. 7 | 8 | By taking a cue from the world of [three-valued logics](https://en.wikipedia.org/wiki/Three-valued_logic), 9 | we can define a couple operators that make working with 10 | `Bool?` values much nicer. 11 | */ 12 | 13 | import Foundation 14 | 15 | func && (lhs: Bool?, rhs: Bool?) -> Bool? { 16 | switch (lhs, rhs) { 17 | case (false, _), (_, false): 18 | return false 19 | case let (unwrapLhs?, unwrapRhs?): 20 | return unwrapLhs && unwrapRhs 21 | default: 22 | return nil 23 | } 24 | } 25 | 26 | func || (lhs: Bool?, rhs: Bool?) -> Bool? { 27 | switch (lhs, rhs) { 28 | case (true, _), (_, true): 29 | return true 30 | case let (unwrapLhs?, unwrapRhs?): 31 | return unwrapLhs || unwrapRhs 32 | default: 33 | return nil 34 | } 35 | } 36 | 37 | false && nil // false 38 | true && nil // nil 39 | [true, nil, false].reduce(true, &&) // false 40 | 41 | nil || true // true 42 | nil || false // nil 43 | [true, nil, false].reduce(false, ||) // true 44 | 45 | //: [Next](@next) 46 | -------------------------------------------------------------------------------- /SwiftTips.playground/Pages/31 - Debouncing a function call.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | //: [Previous](@previous) 2 | 3 | /* 4 | Debouncing is a very useful tool when dealing with UI inputs. 5 | Consider a search bar, whose content is used to query an API. 6 | It wouldn't make sense to perform a request for every character 7 | the user is typing, because as soon as a new character is entered, 8 | the result of the previous request has become irrelevant. 9 | 10 | Instead, our code will perform much better if we "debounce" the 11 | API call, meaning that we will wait until some delay has passed, 12 | without the input being modified, before actually performing the call. 13 | */ 14 | 15 | import Foundation 16 | import PlaygroundSupport 17 | 18 | PlaygroundPage.current.needsIndefiniteExecution = true 19 | 20 | func debounced(delay: TimeInterval, queue: DispatchQueue = .main, action: @escaping (() -> Void)) -> () -> Void { 21 | var workItem: DispatchWorkItem? 22 | 23 | return { 24 | workItem?.cancel() 25 | workItem = DispatchWorkItem(block: action) 26 | queue.asyncAfter(deadline: .now() + delay, execute: workItem!) 27 | } 28 | } 29 | 30 | let debouncedPrint = debounced(delay: 1.0) { print("Action performed!") } 31 | 32 | debouncedPrint() 33 | debouncedPrint() 34 | debouncedPrint() 35 | 36 | // After a 1 second delay, this gets 37 | // printed only once to the console: 38 | 39 | // Action performed! 40 | 41 | //: [Next](@next) 42 | -------------------------------------------------------------------------------- /SwiftTips.playground/Pages/32 - Performing animations sequentially.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | //: [Previous](@previous) 2 | 3 | /* 4 | `UIKit` exposes a very powerful and simple API to perform 5 | view animations. However, this API can become a little bit 6 | quirky to use when we want to perform animations sequentially, 7 | because it involves nesting closure within one another, which 8 | produces notoriously hard to maintain code. 9 | 10 | Nonetheless, it's possible to define a rather simple class, 11 | that will expose a really nicer API for this particular use case 👌 12 | */ 13 | 14 | import Foundation 15 | import UIKit 16 | 17 | class AnimationSequence { 18 | typealias Animations = () -> Void 19 | 20 | private let current: Animations 21 | private let duration: TimeInterval 22 | private var next: AnimationSequence? = nil 23 | 24 | init(animations: @escaping Animations, duration: TimeInterval) { 25 | self.current = animations 26 | self.duration = duration 27 | } 28 | 29 | @discardableResult func append(animations: @escaping Animations, duration: TimeInterval) -> AnimationSequence { 30 | var lastAnimation = self 31 | while let nextAnimation = lastAnimation.next { 32 | lastAnimation = nextAnimation 33 | } 34 | lastAnimation.next = AnimationSequence(animations: animations, duration: duration) 35 | return self 36 | } 37 | 38 | func run() { 39 | UIView.animate(withDuration: duration, animations: current, completion: { finished in 40 | if finished, let next = self.next { 41 | next.run() 42 | } 43 | }) 44 | } 45 | } 46 | 47 | var firstView = UIView() 48 | var secondView = UIView() 49 | 50 | firstView.alpha = 0 51 | secondView.alpha = 0 52 | 53 | AnimationSequence(animations: { firstView.alpha = 1.0 }, duration: 1) 54 | .append(animations: { secondView.alpha = 1.0 }, duration: 0.5) 55 | .append(animations: { firstView.alpha = 0.0 }, duration: 2.0) 56 | .run() 57 | 58 | //: [Next](@next) 59 | -------------------------------------------------------------------------------- /SwiftTips.playground/Pages/33 - Small footprint type-erasing with functions.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | //: [Previous](@previous) 2 | 3 | /* 4 | Seasoned Swift developers know it: a protocol with associated 5 | type (PAT) "can only be used as a generic constraint because 6 | it has Self or associated type requirements". When we really 7 | need to use a PAT to type a variable, the goto workaround is 8 | to use a [type-erased wrapper](https://academy.realm.io/posts/type-erased-wrappers-in-swift/). 9 | 10 | While this solution works perfectly, it requires a fair amount 11 | of boilerplate code. In instances where we are only interested 12 | in exposing one particular function of the PAT, a shorter 13 | approach using function types is possible. 14 | */ 15 | 16 | import Foundation 17 | import UIKit 18 | 19 | protocol Configurable { 20 | associatedtype Model 21 | 22 | func configure(with model: Model) 23 | } 24 | 25 | typealias Configurator = (Model) -> () 26 | 27 | extension UILabel: Configurable { 28 | func configure(with model: String) { 29 | self.text = model 30 | } 31 | } 32 | 33 | let label = UILabel() 34 | let configurator: Configurator = label.configure 35 | 36 | configurator("Foo") 37 | 38 | label.text // "Foo" 39 | 40 | //: [Next](@next) 41 | -------------------------------------------------------------------------------- /SwiftTips.playground/Pages/34 - Asserting that classes have associated NIBs and vice-versa.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | //: [Previous](@previous) 2 | 3 | /* 4 | Most of the time, when we create a `.xib` file, we give it the 5 | same name as its associated class. From that, if we later 6 | refactor our code and rename such a class, we run the risk of 7 | forgetting to rename the associated `.xib`. 8 | 9 | While the error will often be easy to catch, if the `.xib` is 10 | used in a remote section of its app, it might go unnoticed for 11 | sometime. Fortunately it's possible to build custom test 12 | predicates that will assert that 1) for a given class, there 13 | exists a `.nib` with the same name in a given `Bundle`, 2) for 14 | all the `.nib` in a given `Bundle`, there exists a class with 15 | the same name. 16 | */ 17 | 18 | import XCTest 19 | 20 | public func XCTAssertClassHasNib(_ class: AnyClass, bundle: Bundle, file: StaticString = #file, line: UInt = #line) { 21 | let associatedNibURL = bundle.url(forResource: String(describing: `class`), withExtension: "nib") 22 | 23 | XCTAssertNotNil(associatedNibURL, "Class \"\(`class`)\" has no associated nib file", file: file, line: line) 24 | } 25 | 26 | public func XCTAssertNibHaveClasses(_ bundle: Bundle, file: StaticString = #file, line: UInt = #line) { 27 | guard let bundleName = bundle.infoDictionary?["CFBundleName"] as? String, 28 | let basePath = bundle.resourcePath, 29 | let enumerator = FileManager.default.enumerator(at: URL(fileURLWithPath: basePath), 30 | includingPropertiesForKeys: nil, 31 | options: [.skipsHiddenFiles, .skipsSubdirectoryDescendants]) else { return } 32 | 33 | var nibFilesURLs = [URL]() 34 | 35 | for case let fileURL as URL in enumerator { 36 | if fileURL.pathExtension.uppercased() == "NIB" { 37 | nibFilesURLs.append(fileURL) 38 | } 39 | } 40 | 41 | nibFilesURLs.map { $0.lastPathComponent } 42 | .compactMap { $0.split(separator: ".").first } 43 | .map { String($0) } 44 | .forEach { 45 | let associatedClass: AnyClass? = bundle.classNamed("\(bundleName).\($0)") 46 | 47 | XCTAssertNotNil(associatedClass, "File \"\($0).nib\" has no associated class", file: file, line: line) 48 | } 49 | } 50 | 51 | XCTAssertClassHasNib(MyFirstTableViewCell.self, bundle: Bundle(for: AppDelegate.self)) 52 | XCTAssertClassHasNib(MySecondTableViewCell.self, bundle: Bundle(for: AppDelegate.self)) 53 | 54 | XCTAssertNibHaveClasses(Bundle(for: AppDelegate.self)) 55 | 56 | //: [Next](@next) 57 | -------------------------------------------------------------------------------- /SwiftTips.playground/Pages/35 - Defining a union type.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | //: [Previous](@previous) 2 | 3 | /* 4 | The C language has a construct called `union`, that allows 5 | a single variable to hold values from different types. While 6 | Swift does not provide such a construct, it provides enums 7 | with associated values, which allows us to define a type 8 | called `Either` that implements a `union` of two types. 9 | */ 10 | 11 | import Foundation 12 | 13 | enum Either { 14 | case left(A) 15 | case right(B) 16 | 17 | func either(ifLeft: ((A) -> Void)? = nil, ifRight: ((B) -> Void)? = nil) { 18 | switch self { 19 | case let .left(a): 20 | ifLeft?(a) 21 | case let .right(b): 22 | ifRight?(b) 23 | } 24 | } 25 | } 26 | 27 | extension Bool { static func random() -> Bool { return arc4random_uniform(2) == 0 } } 28 | 29 | var intOrString: Either = Bool.random() ? .left(2) : .right("Foo") 30 | 31 | intOrString.either(ifLeft: { print($0 + 1) }, ifRight: { print($0 + "Bar") }) 32 | 33 | //: [Next](@next) 34 | -------------------------------------------------------------------------------- /SwiftTips.playground/Pages/36 - Avoiding hardcoded reuse identifiers.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | //: [Previous](@previous) 2 | 3 | /* 4 | UI components such as `UITableView` and `UICollectionView` 5 | rely on reuse identifiers in order to efficiently recycle 6 | the views they display. Often, those reuse identifiers 7 | take the form of a static hardcoded `String`, that will be 8 | used for every instance of their class. 9 | 10 | Through protocol-oriented programing, it's possible to avoid 11 | those hardcoded values, and instead use the name of the type 12 | as a reuse identifier. 13 | */ 14 | 15 | import Foundation 16 | import UIKit 17 | 18 | protocol Reusable { 19 | static var reuseIdentifier: String { get } 20 | } 21 | 22 | extension Reusable { 23 | static var reuseIdentifier: String { 24 | return String(describing: self) 25 | } 26 | } 27 | 28 | extension UITableViewCell: Reusable { } 29 | 30 | extension UITableView { 31 | func register(_ class: T.Type) { 32 | register(`class`, forCellReuseIdentifier: T.reuseIdentifier) 33 | } 34 | func dequeueReusableCell(for indexPath: IndexPath) -> T { 35 | return dequeueReusableCell(withIdentifier: T.reuseIdentifier, for: indexPath) as! T 36 | } 37 | } 38 | 39 | class MyCell: UITableViewCell { } 40 | 41 | let tableView = UITableView() 42 | 43 | tableView.register(MyCell.self) 44 | let myCell: MyCell = tableView.dequeueReusableCell(for: [0, 0]) 45 | 46 | //: [Next](@next) 47 | -------------------------------------------------------------------------------- /SwiftTips.playground/Pages/37 - Optimizing the use of `reduce()`.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | //: [Previous](@previous) 2 | 3 | /* 4 | Functional programing is a great way to simplify a codebase. 5 | For instance, `reduce` is an alternative to the classic `for` 6 | loop, without most the boilerplate. Unfortunately, simplicity 7 | often comes at the price of performance. 8 | 9 | Consider that you want to remove duplicate values from 10 | a `Sequence`. While `reduce()` is a perfectly fine way to 11 | express this computation, the performance will be sub optimal, 12 | because of all the unnecessary array copying that will happen 13 | every time its closure gets called. 14 | 15 | That's when `reduce(into:_:)` comes into play. This version of 16 | `reduce` leverages the capacities of copy-on-write type (such 17 | as `Array` or `Dictionnary`) in order to avoid unnecessary 18 | copying, which results in a great performance boost. 19 | */ 20 | 21 | import Foundation 22 | 23 | func time(averagedExecutions: Int = 1, _ code: () -> Void) { 24 | let start = Date() 25 | for _ in 0.. Void) rethrows { 19 | var stop = false 20 | for element in self { 21 | try body(element, &stop) 22 | 23 | if stop { 24 | return 25 | } 26 | } 27 | } 28 | } 29 | 30 | ["Foo", "Bar", "FooBar"].forEach { element, stop in 31 | print(element) 32 | stop = (element == "Bar") 33 | } 34 | 35 | // Prints: 36 | // Foo 37 | // Bar 38 | 39 | //: [Next](@next) 40 | -------------------------------------------------------------------------------- /SwiftTips.playground/Pages/39 - Using `typealias` to its fullest.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | //: [Previous](@previous) 2 | 3 | /* 4 | The keyword `typealias` allows developers to give a new 5 | name to an already existing type. For instance, Swift 6 | defines `Void` as a `typealias` of `()`, the empty tuple. 7 | 8 | But a less known feature of this mechanism is that it 9 | allows to assign concrete types to generic parameters, 10 | or to rename them. This can help make the semantics of 11 | generic types much clearer, when used in specific use cases. 12 | */ 13 | 14 | import Foundation 15 | 16 | enum Either { 17 | case left(Left) 18 | case right(Right) 19 | } 20 | 21 | typealias Result = Either 22 | 23 | typealias IntOrString = Either 24 | 25 | //: [Next](@next) 26 | -------------------------------------------------------------------------------- /SwiftTips.playground/Pages/40 - Lightweight data-binding for an MVVM implementation.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | //: [Previous](@previous) 2 | 3 | /* 4 | MVVM is a great pattern to separate business logic from 5 | presentation logic. The main challenge to make it work, 6 | is to define a mechanism for the presentation layer to 7 | be notified of model updates. 8 | 9 | [RxSwift](https://github.com/ReactiveX/RxSwift) is a 10 | perfect choice to solve such a problem. Yet, some 11 | developers don't feel confortable with leveraging a 12 | third-party library for such a central part of their 13 | architecture. 14 | 15 | For those situation, it's possible to define a 16 | lightweight `Variable` type, that will make the MVVM 17 | pattern very easy to use! 18 | */ 19 | 20 | import Foundation 21 | 22 | class Variable { 23 | var value: Value { 24 | didSet { 25 | onUpdate?(value) 26 | } 27 | } 28 | 29 | var onUpdate: ((Value) -> Void)? { 30 | didSet { 31 | onUpdate?(value) 32 | } 33 | } 34 | 35 | init(_ value: Value, _ onUpdate: ((Value) -> Void)? = nil) { 36 | self.value = value 37 | self.onUpdate = onUpdate 38 | self.onUpdate?(value) 39 | } 40 | } 41 | 42 | let variable: Variable = Variable(nil) 43 | 44 | variable.onUpdate = { data in 45 | if let data = data { 46 | print(data) 47 | } 48 | } 49 | 50 | variable.value = "Foo" 51 | variable.value = "Bar" 52 | 53 | // prints: 54 | // Foo 55 | // Bar 56 | 57 | //: [Next](@next) 58 | -------------------------------------------------------------------------------- /SwiftTips.playground/Pages/41 - Bringing some type-safety to a userInfo Dictionary.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | //: [Previous](@previous) 2 | 3 | /* 4 | Many iOS APIs still rely on a `userInfo` `Dictionary` 5 | to handle use-case specific data. This `Dictionary` 6 | usually stores untyped values, and is declared as 7 | follows: `[String: Any]` (or sometimes `[AnyHashable: Any]`. 8 | 9 | Retrieving data from such a structure will involve 10 | some conditional casting (via the `as?` operator), 11 | which is prone to both errors and repetitions. Yet, 12 | by introducing a custom `subscript`, it's possible 13 | to encapsulate all the tedious logic, and end-up 14 | with an easier and more robust API. 15 | */ 16 | 17 | import Foundation 18 | 19 | typealias TypedUserInfoKey = (key: String, type: T.Type) 20 | 21 | extension Dictionary where Key == String, Value == Any { 22 | subscript(_ typedKey: TypedUserInfoKey) -> T? { 23 | return self[typedKey.key] as? T 24 | } 25 | } 26 | 27 | let userInfo: [String : Any] = ["Foo": 4, "Bar": "forty-two"] 28 | 29 | let integerTypedKey = TypedUserInfoKey(key: "Foo", type: Int.self) 30 | let intValue = userInfo[integerTypedKey] // returns 4 31 | type(of: intValue) // returns Int? 32 | 33 | let stringTypedKey = TypedUserInfoKey(key: "Bar", type: String.self) 34 | let stringValue = userInfo[stringTypedKey] // returns "forty-two" 35 | type(of: stringValue) // returns String? 36 | 37 | //: [Next](@next) 38 | -------------------------------------------------------------------------------- /SwiftTips.playground/Pages/42 - Using KeyPaths instead of closures.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | //: [Previous](@previous) 2 | 3 | /* 4 | Closures are a great way to interact with generic APIs, 5 | for instance APIs that allow to manipulate data 6 | structures through the use of generic functions, such as 7 | `filter()` or `sorted()`. 8 | 9 | The annoying part is that closures tend to clutter your 10 | code with many instances of `{`, `}` and `$0`, which can 11 | quickly undermine its readably. 12 | 13 | A nice alternative for a cleaner syntax is to use a 14 | `KeyPath` instead of a closure, along with an operator 15 | that will deal with transforming the provided `KeyPath` 16 | in a closure. 17 | */ 18 | 19 | import Foundation 20 | 21 | prefix operator ^ 22 | 23 | prefix func ^ (_ keyPath: KeyPath) -> (Element) -> Attribute { 24 | return { element in element[keyPath: keyPath] } 25 | } 26 | 27 | struct MyData { 28 | let int: Int 29 | let string: String 30 | } 31 | 32 | let data = [MyData(int: 2, string: "Foo"), MyData(int: 4, string: "Bar")] 33 | 34 | data.map(^\.int) // [2, 4] 35 | data.map(^\.string) // ["Foo", "Bar"] 36 | 37 | //: [Next](@next) 38 | -------------------------------------------------------------------------------- /SwiftTips.playground/Pages/43 - Transform an asynchronous function into a synchronous one.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | //: [Previous](@previous) 2 | 3 | /* 4 | Asynchronous functions are a great way to deal with future 5 | events without blocking a thread. Yet, there are times 6 | where we would like them to behave in exactly such a 7 | blocking way. 8 | 9 | Think about writing unit tests and using mocked network calls. 10 | You will need to add complexity to your test in order to deal 11 | with asynchronous functions, whereas synchronous ones would 12 | be much easier to manage. 13 | 14 | Thanks to Swift proficiency in the functional paradigm, it is 15 | possible to write a function whose job is to take an 16 | asynchronous function and transform it into a synchronous one. 17 | */ 18 | import Foundation 19 | 20 | func makeSynchrone(_ asyncFunction: @escaping (A, (B) -> Void) -> Void) -> (A) -> B { 21 | return { arg in 22 | let lock = NSRecursiveLock() 23 | 24 | var result: B? = nil 25 | 26 | asyncFunction(arg) { 27 | result = $0 28 | lock.unlock() 29 | } 30 | 31 | lock.lock() 32 | 33 | return result! 34 | } 35 | } 36 | 37 | func myAsyncFunction(arg: Int, completionHandler: (String) -> Void) { 38 | completionHandler("🎉 \(arg)") 39 | } 40 | 41 | let syncFunction = makeSynchrone(myAsyncFunction) 42 | 43 | print(syncFunction(42)) // prints 🎉 42 44 | 45 | //: [Next](@next) 46 | -------------------------------------------------------------------------------- /SwiftTips.playground/Pages/44 - Solving callback hell with function composition.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | //: [Previous](@previous) 2 | 3 | /* 4 | Asynchronous functions are a big part of iOS APIs, and most 5 | developers are familiar with the challenge they pose when 6 | one needs to sequentially call several asynchronous APIs. 7 | 8 | This often results in callbacks being nested into one another, 9 | a predicament often referred to as callback hell. 10 | 11 | Many third-party frameworks are able to tackle this issue, 12 | for instance [RxSwift](https://github.com/ReactiveX/RxSwift) 13 | or [PromiseKit](https://github.com/mxcl/PromiseKit). 14 | Yet, for simple instances of the problem, there is no need 15 | to use such big guns, as it can actually be solved with 16 | simple function composition. 17 | */ 18 | 19 | import Foundation 20 | 21 | typealias CompletionHandler = (Result?, Error?) -> Void 22 | 23 | infix operator ~>: MultiplicationPrecedence 24 | 25 | func ~> (_ first: @escaping (CompletionHandler) -> Void, _ second: @escaping (T, CompletionHandler) -> Void) -> (CompletionHandler) -> Void { 26 | return { completion in 27 | first({ firstResult, error in 28 | guard let firstResult = firstResult else { completion(nil, error); return } 29 | 30 | second(firstResult, { (secondResult, error) in 31 | completion(secondResult, error) 32 | }) 33 | }) 34 | } 35 | } 36 | 37 | func ~> (_ first: @escaping (CompletionHandler) -> Void, _ transform: @escaping (T) -> U) -> (CompletionHandler) -> Void { 38 | return { completion in 39 | first({ result, error in 40 | guard let result = result else { completion(nil, error); return } 41 | 42 | completion(transform(result), nil) 43 | }) 44 | } 45 | } 46 | 47 | func service1(_ completionHandler: CompletionHandler) { 48 | completionHandler(42, nil) 49 | } 50 | 51 | func service2(arg: String, _ completionHandler: CompletionHandler) { 52 | completionHandler("🎉 \(arg)", nil) 53 | } 54 | 55 | let chainedServices = service1 56 | ~> { int in return String(int / 2) } 57 | ~> service2 58 | 59 | chainedServices({ result, _ in 60 | guard let result = result else { return } 61 | 62 | print(result) // Prints: 🎉 21 63 | }) 64 | 65 | //: [Next](@next) 66 | -------------------------------------------------------------------------------- /SwiftTips.playground/Pages/45 - Getting rid of overabundant `[weak self]` and `guard`.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | //: [Previous](@previous) 2 | 3 | /* 4 | Callbacks are a part of almost all iOS apps, and as frameworks 5 | such as `RxSwift` keep gaining in popularity, they become ever 6 | more present in our codebase. 7 | 8 | Seasoned Swift developers are aware of the potential memory 9 | leaks that `@escaping` callbacks can produce, so they make 10 | real sure to always use `[weak self]`, whenever they need to 11 | use `self` inside such a context. And when they need to have 12 | `self` be non-optional, they then add a `guard` statement along. 13 | 14 | Consequently, this syntax of a `[weak self]` followed by 15 | a `guard` rapidly tends to appear everywhere in the codebase. 16 | The good thing is that, through a little protocol-oriented 17 | trick, it's actually possible to get rid of this tedious 18 | syntax, without loosing any of its benefits! 19 | */ 20 | 21 | import Foundation 22 | import PlaygroundSupport 23 | 24 | PlaygroundPage.current.needsIndefiniteExecution = true 25 | 26 | protocol Weakifiable: class { } 27 | 28 | extension Weakifiable { 29 | func weakify(_ code: @escaping (Self) -> Void) -> () -> Void { 30 | return { [weak self] in 31 | guard let self = self else { return } 32 | 33 | code(self) 34 | } 35 | } 36 | 37 | func weakify(_ code: @escaping (T, Self) -> Void) -> (T) -> Void { 38 | return { [weak self] arg in 39 | guard let self = self else { return } 40 | 41 | code(arg, self) 42 | } 43 | } 44 | } 45 | 46 | extension NSObject: Weakifiable { } 47 | 48 | class Producer: NSObject { 49 | 50 | deinit { 51 | print("deinit Producer") 52 | } 53 | 54 | private var handler: (Int) -> Void = { _ in } 55 | 56 | func register(handler: @escaping (Int) -> Void) { 57 | self.handler = handler 58 | 59 | DispatchQueue.main.asyncAfter(deadline: .now() + 1.0, execute: { self.handler(42) }) 60 | } 61 | } 62 | 63 | class Consumer: NSObject { 64 | 65 | deinit { 66 | print("deinit Consumer") 67 | } 68 | 69 | let producer = Producer() 70 | 71 | func consume() { 72 | producer.register(handler: weakify { result, strongSelf in 73 | strongSelf.handle(result) 74 | }) 75 | } 76 | 77 | private func handle(_ result: Int) { 78 | print("🎉 \(result)") 79 | } 80 | } 81 | 82 | var consumer: Consumer? = Consumer() 83 | 84 | consumer?.consume() 85 | 86 | DispatchQueue.main.asyncAfter(deadline: .now() + 2.0, execute: { consumer = nil }) 87 | 88 | // This code prints: 89 | // 🎉 42 90 | // deinit Consumer 91 | // deinit Producer 92 | 93 | //: [Next](@next) 94 | -------------------------------------------------------------------------------- /SwiftTips.playground/Pages/46 - Lightweight dependency injection through protocol-oriented programming.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | //: [Previous](@previous) 2 | 3 | /* 4 | Singletons are pretty bad. They make your architecture rigid 5 | and tightly coupled, which then results in your code being 6 | hard to test and refactor. Instead of using singletons, your 7 | code should rely on dependency injection, which is a much more 8 | architecturally sound approach. 9 | 10 | But singletons are so easy to use, and dependency injection 11 | requires us to do extra-work. So maybe, for simple situations, 12 | we could find an in-between solution? 13 | 14 | One possible solution is to rely on one of Swift's most know 15 | features: protocol-oriented programming. Using a `protocol`, 16 | we declare and access our dependency. We then store it in a 17 | private singleton, and perform the injection through an 18 | extension of said `protocol`. 19 | 20 | This way, our code will indeed be decoupled from its dependency, 21 | while at the same time keeping the boilerplate to a minimum. 22 | */ 23 | 24 | import Foundation 25 | 26 | protocol Formatting { 27 | var formatter: NumberFormatter { get } 28 | } 29 | 30 | private let sharedFormatter: NumberFormatter = { 31 | let sharedFormatter = NumberFormatter() 32 | sharedFormatter.numberStyle = .currency 33 | return sharedFormatter 34 | }() 35 | 36 | extension Formatting { 37 | var formatter: NumberFormatter { return sharedFormatter } 38 | } 39 | 40 | class ViewModel: Formatting { 41 | var displayableAmount: String? 42 | 43 | func updateDisplay(to amount: Double) { 44 | displayableAmount = formatter.string(for: amount) 45 | } 46 | } 47 | 48 | let viewModel = ViewModel() 49 | 50 | viewModel.updateDisplay(to: 42000.45) 51 | viewModel.displayableAmount // "$42,000.45" 52 | 53 | //: [Next](@next) 54 | -------------------------------------------------------------------------------- /SwiftTips.playground/Pages/47 - Another lightweight dependency injection through default values for function parameters.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | //: [Previous](@previous) 2 | 3 | /* 4 | Dependency injection boils down to a simple idea: when an 5 | object requires a dependency, it shouldn't create it by 6 | itself, but instead it should be given a function that does 7 | it for him. 8 | 9 | Now the great thing with Swift is that, not only can a 10 | function take another function as a parameter, but that 11 | parameter can also be given a default value. 12 | 13 | When you combine both those features, you can end up with 14 | a dependency injection pattern that is both lightweight on 15 | boilerplate, but also type safe. 16 | */ 17 | 18 | import Foundation 19 | 20 | protocol Service { 21 | func call() -> String 22 | } 23 | 24 | class ProductionService: Service { 25 | func call() -> String { 26 | return "This is the production" 27 | } 28 | } 29 | 30 | class MockService: Service { 31 | func call() -> String { 32 | return "This is a mock" 33 | } 34 | } 35 | 36 | typealias Provider = () -> T 37 | 38 | class Controller { 39 | 40 | let service: Service 41 | 42 | init(serviceProvider: Provider = { return ProductionService() }) { 43 | self.service = serviceProvider() 44 | } 45 | 46 | func work() { 47 | print(service.call()) 48 | } 49 | } 50 | 51 | let productionController = Controller() 52 | productionController.work() // prints "This is the production" 53 | 54 | let mockedController = Controller(serviceProvider: { return MockService() }) 55 | mockedController.work() // prints "This is a mock" 56 | 57 | //: [Next](@next) 58 | -------------------------------------------------------------------------------- /SwiftTips.playground/Pages/48 - Providing a default value to a `Decodable` `enum`.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | //: [Previous](@previous) 2 | 3 | /* 4 | Swift's `Codable` framework does a great job at seamlessly 5 | decoding entities from a JSON stream. However, when we 6 | integrate web-services, we are sometimes left to deal with 7 | JSONs that require behaviors that `Codable` does not provide 8 | out-of-the-box. 9 | 10 | For instance, we might have a string-based or integer-based 11 | `enum`, and be required to set it to a default value when 12 | the data found in the JSON does not match any of its cases. 13 | 14 | We might be tempted to implement this via an extensive 15 | `switch` statement over all the possible cases, but there 16 | is a much shorter alternative through the initializer `init?(rawValue:)`: 17 | */ 18 | 19 | import Foundation 20 | 21 | enum State: String, Decodable { 22 | case active 23 | case inactive 24 | case undefined 25 | 26 | init(from decoder: Decoder) throws { 27 | let container = try decoder.singleValueContainer() 28 | let decodedString = try container.decode(String.self) 29 | 30 | self = State(rawValue: decodedString) ?? .undefined 31 | } 32 | } 33 | 34 | let data = """ 35 | ["active", "inactive", "foo"] 36 | """.data(using: .utf8)! 37 | 38 | let decoded = try! JSONDecoder().decode([State].self, from: data) 39 | 40 | print(decoded) // [State.active, State.inactive, State.undefined] 41 | 42 | //: [Next](@next) 43 | -------------------------------------------------------------------------------- /SwiftTips.playground/Pages/49 - Using `Never` to represent impossible code paths.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | //: [Previous](@previous) 2 | 3 | /* 4 | `Never` is quite a peculiar type in the Swift Standard 5 | Library: it is defined as an empty enum `enum Never { }`. 6 | 7 | While this might seem odd at first glance, it actually 8 | yields a very interesting property: it makes it a type 9 | that cannot be constructed (i.e. it possesses no instances). 10 | 11 | This way, `Never` can be used as a generic parameter to 12 | let the compiler know that a particular feature will not 13 | be used. 14 | */ 15 | 16 | import Foundation 17 | 18 | enum Result { 19 | case success(value: Value) 20 | case failure(error: Error) 21 | } 22 | 23 | func willAlwaysSucceed(_ completion: @escaping ((Result) -> Void)) { 24 | completion(.success(value: "Call was successful")) 25 | } 26 | 27 | willAlwaysSucceed( { result in 28 | switch result { 29 | case .success(let value): 30 | print(value) 31 | // the compiler knows that the `failure` case cannot happen 32 | // so it doesn't require us to handle it. 33 | } 34 | }) 35 | 36 | //: [Next](@next) 37 | -------------------------------------------------------------------------------- /SwiftTips.playground/Pages/50 - Implementing a namespace through an empty `enum`.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | //: [Previous](@previous) 2 | 3 | /* 4 | Swift does not really have an out-of-the-box support 5 | of namespaces. One could argue that a Swift module 6 | can be seen as a namespace, but creating a dedicated 7 | Framework for this sole purpose can legitimately be 8 | regarded as overkill. 9 | 10 | Some developers have taken the habit to use a `struct` 11 | which only contains `static` fields to implement a 12 | namespace. While this does the job, it requires us to 13 | remember to implement an empty `private` `init()`, 14 | because it wouldn't make sense for such a `struct` to 15 | be instantiated. 16 | 17 | It's actually possible to take this approach one step 18 | further, by replacing the `struct` with an `enum`. 19 | While it might seem weird to have an `enum` with no 20 | `case`, it's actually a [very idiomatic way](https://github.com/apple/swift/blob/a4230ab2ad37e37edc9ed86cd1510b7c016a769d/stdlib/public/core/Unicode.swift#L918) 21 | to declare a type that cannot be instantiated. 22 | */ 23 | 24 | import Foundation 25 | 26 | enum NumberFormatterProvider { 27 | static var currencyFormatter: NumberFormatter { 28 | let formatter = NumberFormatter() 29 | formatter.numberStyle = .currency 30 | formatter.roundingIncrement = 0.01 31 | return formatter 32 | } 33 | 34 | static var decimalFormatter: NumberFormatter { 35 | let formatter = NumberFormatter() 36 | formatter.numberStyle = .decimal 37 | formatter.decimalSeparator = "," 38 | return formatter 39 | } 40 | } 41 | 42 | NumberFormatterProvider() // ❌ impossible to instantiate by mistake 43 | 44 | NumberFormatterProvider.currencyFormatter.string(from: 2.456) // $2.46 45 | NumberFormatterProvider.decimalFormatter.string(from: 2.456) // 2,456 46 | 47 | //: [Next](@next) 48 | -------------------------------------------------------------------------------- /SwiftTips.playground/Pages/51 - Defining a custom `init` without loosing the compiler-generated one.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | //: [Previous](@previous) 2 | 3 | /* 4 | It's common knowledge for Swift developers that, 5 | when you define a `struct`, the compiler is going 6 | to automatically generate a memberwise `init` for 7 | you. That is, unless you also define an `init` of 8 | your own. Because then, the compiler won't 9 | generate any memberwise `init`. 10 | 11 | Yet, there are many instances where we might enjoy 12 | the opportunity to get both. As it turns out, this 13 | goal is quite easy to achieve: you just need to 14 | define your own `init` in an `extension` rather 15 | than inside the type definition itself. 16 | */ 17 | 18 | import Foundation 19 | 20 | struct Point { 21 | let x: Int 22 | let y: Int 23 | } 24 | 25 | extension Point { 26 | init() { 27 | x = 0 28 | y = 0 29 | } 30 | } 31 | 32 | let usingDefaultInit = Point(x: 4, y: 3) 33 | let usingCustomInit = Point() 34 | 35 | //: [Next](@next) 36 | -------------------------------------------------------------------------------- /SwiftTips.playground/Pages/52 - Avoiding double negatives within `guard` statements.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | //: [Previous](@previous) 2 | 3 | /* 4 | A `guard` statement is a very convenient way for 5 | the developer to assert that a condition is met, 6 | in order for the execution of the program to keep 7 | going. 8 | 9 | However, since the body of a `guard` statement is 10 | meant to be executed when the condition evaluates 11 | to `false`, the use of the negation (`!`) operator 12 | within the condition of a `guard` statement can 13 | make the code hard to read, as it becomes a double 14 | negative. 15 | 16 | A nice trick to avoid such double negatives is to 17 | encapsulate the use of the `!` operator within a 18 | new property or function, whose name does not 19 | include a negative. 20 | */ 21 | 22 | import Foundation 23 | 24 | extension Collection { 25 | var hasElements: Bool { 26 | return !isEmpty 27 | } 28 | } 29 | 30 | let array = Bool.random() ? [1, 2, 3] : [] 31 | 32 | guard array.hasElements else { fatalError("array was empty") } 33 | 34 | print(array) 35 | 36 | //: [Next](@next) 37 | -------------------------------------------------------------------------------- /SwiftTips.playground/Pages/53 - Using `switch` and `if` as expressions.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | //: [Previous](@previous) 2 | 3 | /* 4 | Contrary to other languages, like Kotlin, Swift 5 | does not allow `switch` and `if` to be used as 6 | expressions. Meaning that the following code is 7 | not valid Swift: 8 | 9 | ```swift 10 | let constant = if condition { 11 | someValue 12 | } else { 13 | someOtherValue 14 | } 15 | ``` 16 | 17 | A common solution to this problem is to wrap the 18 | `if` or `switch` statement within a closure, that 19 | will then be immediately called. While this 20 | approach does manage to achieve the desired goal, 21 | it makes for a rather poor syntax. 22 | 23 | To avoid the ugly trailing `()` and improve on the 24 | readability, you can define a `resultOf` function, 25 | that will serve the exact same purpose, in a more 26 | elegant way. 27 | */ 28 | 29 | import Foundation 30 | 31 | func resultOf(_ code: () -> T) -> T { 32 | return code() 33 | } 34 | 35 | let randomInt = Int.random(in: 0...3) 36 | 37 | let spelledOut: String = resultOf { 38 | switch randomInt { 39 | case 0: 40 | return "Zero" 41 | case 1: 42 | return "One" 43 | case 2: 44 | return "Two" 45 | case 3: 46 | return "Three" 47 | default: 48 | return "Out of range" 49 | } 50 | } 51 | 52 | print(spelledOut) 53 | 54 | //: [Next](@next) 55 | -------------------------------------------------------------------------------- /SwiftTips.playground/Pages/54 - Composing `NSAttributedString` through a Function Builder.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | //: [Previous](@previous) 2 | 3 | /* 4 | Swift 5.1 introduced Function Builders: a great 5 | tool for building custom DSL syntaxes, like SwiftUI. 6 | However, one doesn't need to be building a 7 | full-fledged DSL in order to leverage them. 8 | 9 | For example, it's possible to write a simple 10 | Function Builder, whose job will be to compose 11 | together individual instances of 12 | `NSAttributedString` through a nicer syntax than 13 | the standard API. 14 | */ 15 | 16 | import UIKit 17 | 18 | @_functionBuilder 19 | class NSAttributedStringBuilder { 20 | static func buildBlock(_ components: NSAttributedString...) -> NSAttributedString { 21 | let result = NSMutableAttributedString(string: "") 22 | 23 | return components.reduce(into: result) { (result, current) in result.append(current) } 24 | } 25 | } 26 | 27 | extension NSAttributedString { 28 | class func composing(@NSAttributedStringBuilder _ parts: () -> NSAttributedString) -> NSAttributedString { 29 | return parts() 30 | } 31 | } 32 | 33 | let result = NSAttributedString.composing { 34 | NSAttributedString(string: "Hello", 35 | attributes: [.font: UIFont.systemFont(ofSize: 24), 36 | .foregroundColor: UIColor.red]) 37 | NSAttributedString(string: " world!", 38 | attributes: [.font: UIFont.systemFont(ofSize: 20), 39 | .foregroundColor: UIColor.orange]) 40 | } 41 | 42 | result 43 | 44 | //: [Next](@next) 45 | -------------------------------------------------------------------------------- /SwiftTips.playground/Pages/55 - Implementing pseudo-inheritance between `structs`.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | //: [Previous](@previous) 2 | 3 | /* 4 | If you’ve always wanted to use some kind of 5 | inheritance mechanism for your structs, 6 | Swift 5.1 is going to make you very happy! 7 | 8 | Using the new KeyPath-based dynamic member 9 | lookup, you can implement some pseudo-inheritance, 10 | where a type inherits the API of another one 🎉 11 | 12 | (However, be careful, I’m definitely not 13 | advocating inheritance as a go-to solution 🙃) 14 | */ 15 | import Foundation 16 | 17 | protocol Inherits { 18 | associatedtype SuperType 19 | 20 | var `super`: SuperType { get } 21 | } 22 | 23 | extension Inherits { 24 | subscript(dynamicMember keyPath: KeyPath) -> T { 25 | return self.`super`[keyPath: keyPath] 26 | } 27 | } 28 | 29 | struct Person { 30 | let name: String 31 | } 32 | 33 | @dynamicMemberLookup 34 | struct User: Inherits { 35 | let `super`: Person 36 | 37 | let login: String 38 | let password: String 39 | } 40 | 41 | let user = User(super: Person(name: "John Appleseed"), login: "Johnny", password: "1234") 42 | 43 | user.name // "John Appleseed" 44 | user.login // "Johnny" 45 | 46 | //: [Next](@next) 47 | -------------------------------------------------------------------------------- /SwiftTips.playground/Pages/56 - Localization through `String` interpolation.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | //: [Previous](@previous) 2 | 3 | /* 4 | Swift 5 gave us the possibility to define 5 | our own custom `String` interpolation methods. 6 | 7 | This feature can be used to power many use 8 | cases, but there is one that is guaranteed 9 | to make sense in most projects: localizing 10 | user-facing strings. 11 | */ 12 | 13 | import Foundation 14 | 15 | extension String.StringInterpolation { 16 | mutating func appendInterpolation(localized key: String, _ args: CVarArg...) { 17 | let localized = String(format: NSLocalizedString(key, comment: ""), arguments: args) 18 | appendLiteral(localized) 19 | } 20 | } 21 | 22 | 23 | /* 24 | Let's assume that this is the content of our Localizable.strings: 25 | 26 | "welcome.screen.greetings" = "Hello %@!"; 27 | */ 28 | 29 | let userName = "John" 30 | print("\(localized: "welcome.screen.greetings", userName)") // Hello John! 31 | 32 | //: [Next](@next) 33 | -------------------------------------------------------------------------------- /SwiftTips.playground/Pages/57 - Property Wrappers as Debugging Tools.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | //: [Previous](@previous) 2 | 3 | import Foundation 4 | 5 | /* 6 | Property Wrappers allow developers to wrap 7 | properties with specific behaviors, that 8 | will be seamlessly triggered whenever the 9 | properties are accessed. 10 | 11 | While their primary use case is to implement 12 | business logic within our apps, it's also 13 | possible to use Property Wrappers as debugging tools! 14 | 15 | For example, we could build a wrapper called 16 | `@History`, that would be added to a property 17 | while debugging and would keep track of all 18 | the values set to this property. 19 | */ 20 | 21 | @propertyWrapper 22 | struct History { 23 | private var value: Value 24 | private(set) var history: [Value] = [] 25 | 26 | init(wrappedValue: Value) { 27 | self.value = wrappedValue 28 | } 29 | 30 | var wrappedValue: Value { 31 | get { value } 32 | 33 | set { 34 | history.append(value) 35 | value = newValue 36 | } 37 | } 38 | 39 | var projectedValue: Self { 40 | return self 41 | } 42 | } 43 | 44 | // We can then decorate our business code 45 | // with the `@History` wrapper 46 | struct User { 47 | @History var name: String = "" 48 | } 49 | 50 | var user = User() 51 | 52 | // All the existing call sites will still 53 | // compile, without the need for any change 54 | user.name = "John" 55 | user.name = "Jane" 56 | 57 | // But now we can also access an history of 58 | // all the previous values! 59 | user.$name.history // ["", "John"] 60 | 61 | //: [Next](@next) 62 | -------------------------------------------------------------------------------- /SwiftTips.playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | --------------------------------------------------------------------------------