1594740720

# Graphical Functions made from an effortless sketch

Hello everyone! A few days ago, I was working on a machine learning model where I needed to input a function relating X and Y. The only constraints were that the function had to be continuous and the bounds for X and Y had to be [0, 1].

With dozens of distinct curves in mind, I started to sketch them out on a paper. The point was to fit them on a graphing calculator afterwards. It was a tedious task and I asked my sister for help.

“Why don’t you write a program for it?”, she replied.

# Purpose

An existing application: MyCurveFit

There are existing applications that take in X and Y coordinates to return the exact equation. However, the more complex the curve is, the more coordinates the user has to key in. Furthermore, the user has to manually choose the function to fit the points (Example: Linear versus Exponential).

#python #scipy #mathematics #functions

1666245660

## Swift tips & tricks ⚡️

One of the things I really love about Swift is how I keep finding interesting ways to use it in various situations, and when I do - I usually share them on Twitter. Here's a collection of all the tips & tricks that I've shared so far. Each entry has a link to the original tweet, if you want to respond with some feedback or question, which is always super welcome! 🚀

⚠️ This list is no longer being updated. For my latest Swift tips, checkout the "Tips" section on Swift by Sundell.

Also make sure to check out all of my other Swift content:

## 102 Making async tests faster and more stable

🚀 Here are some quick tips to make async tests faster & more stable:

• 😴 Avoid sleep() - use expectations instead
• ⏱ Use generous timeouts to avoid flakiness on CI
• 🧐 Put all assertions at the end of each test, not inside closures
``````// BEFORE:

class MentionDetectorTests: XCTestCase {
func testDetectingMention() {
let detector = MentionDetector()
let string = "This test was written by @johnsundell."

detector.detectMentions(in: string) { mentions in
XCTAssertEqual(mentions, ["johnsundell"])
}

sleep(2)
}
}

// AFTER:

class MentionDetectorTests: XCTestCase {
func testDetectingMention() {
let detector = MentionDetector()
let string = "This test was written by @johnsundell."

var mentions: [String]?
let expectation = self.expectation(description: #function)

detector.detectMentions(in: string) {
mentions = \$0
expectation.fulfill()
}

waitForExpectations(timeout: 10)
XCTAssertEqual(mentions, ["johnsundell"])
}
}
``````

For more on async testing, check out "Unit testing asynchronous Swift code".

## 101 Adding support for Apple Pencil double-taps

✍️ Adding support for the new Apple Pencil double-tap feature is super easy! All you have to do is to create a `UIPencilInteraction`, add it to a view, and implement one delegate method. Hopefully all pencil-compatible apps will soon adopt this.

``````let interaction = UIPencilInteraction()
interaction.delegate = self

extension ViewController: UIPencilInteractionDelegate {
func pencilInteractionDidTap(_ interaction: UIPencilInteraction) {
// Handle pencil double-tap
}
}
``````

For more on using this and other iPad Pro features, check out "Building iPad Pro features in Swift".

## 100 Combining values with functions

😎 Here's a cool function that combines a value with a function to return a closure that captures that value, so that it can be called without any arguments. Super useful when working with closure-based APIs and we want to use some of our properties without having to capture `self`.

``````func combine<A, B>(_ value: A, with closure: @escaping (A) -> B) -> () -> B {
return { closure(value) }
}

// BEFORE:

class ProductViewController: UIViewController {

buyButton.handler = { [weak self] in
guard let self = self else {
return
}

self.productManager.startCheckout(for: self.product)
}
}
}

// AFTER:

class ProductViewController: UIViewController {

}
}
``````

## 99 Dependency injection using functions

💉 When I'm only using a single function from a dependency, I love to inject that function as a closure, instead of having to create a protocol and inject the whole object. Makes dependency injection & testing super simple.

``````final class ArticleLoader {
typealias Networking = (Endpoint) -> Future<Data>

private let networking: Networking

init(networking: @escaping Networking = URLSession.shared.load) {
self.networking = networking
}

return networking(.latestArticles).decode()
}
}
``````

For more on this technique, check out "Simple Swift dependency injection with functions".

## 98 Using a custom exception handler

💥 It's cool that you can easily assign a closure as a custom `NSException` handler. This is super useful when building things in Playgrounds - since you can't use breakpoints - so instead of just `signal SIGABRT`, you'll get the full exception description if something goes wrong.

``````NSSetUncaughtExceptionHandler { exception in
print(exception)
}
``````

## 97 Using type aliases to give semantic meaning to primitives

❤️ I love that in Swift, we can use the type system to make our code so much more self-documenting - one way of doing so is to use type aliases to give the primitive types that we use a more semantic meaning.

``````extension List.Item {
// Using type aliases, we can give semantic meaning to the
// primitive types that we use, without having to introduce
// wrapper types.
typealias Index = Int
}

extension List {
enum Mutation {
// Our enum cases now become a lot more self-documenting,
// explain them.
case update(Item, Item.Index)
case remove(Item.Index)
}
}
``````

For more on self-documenting code, check out "Writing self-documenting Swift code".

## 96 Specializing protocols using constraints

🤯 A little late night prototyping session reveals that protocol constraints can not only be applied to extensions - they can also be added to protocol definitions!

This is awesome, since it lets us easily define specialized protocols based on more generic ones.

``````protocol Component {
associatedtype Container
}

// Protocols that inherit from other protocols can include
// constraints to further specialize them.
protocol ViewComponent: Component where Container == UIView {
associatedtype View: UIView
var view: View { get }
}

extension ViewComponent {
}
}
``````

For more on specializing protocols, check out "Specializing protocols in Swift".

## 95 Unwrapping an optional or throwing an error

📦 Here's a super handy extension on Swift's `Optional` type, which gives us a really nice API for easily unwrapping an optional, or throwing an error in case the value turned out to be `nil`:

``````extension Optional {
func orThrow(_ errorExpression: @autoclosure () -> Error) throws -> Wrapped {
switch self {
case .some(let value):
return value
case .none:
throw errorExpression()
}
}
}

let file = try loadFile(at: path).orThrow(MissingFileError())
``````

For more ways that optionals can be extended, check out "Extending optionals in Swift".

## 94 Testing code that uses static APIs

👩‍🔬 Testing code that uses static APIs can be really tricky, but there's a way that it can often be done - using Swift's first class function capabilities!

Instead of accessing that static API directly, we can inject the function we want to use, which enables us to mock it!

``````// BEFORE

func loadFriends(then handler: @escaping (Result<[Friend]>) -> Void) {
...
}
}
}

// AFTER

typealias Handler<T> = (Result<T>) -> Void

then handler: @escaping Handler<[Friend]>) {
...
}
}
}

// MOCKING IN TESTS

handler(.success(mockData))
}

...
}
``````

## 93 Matching multiple enum cases with associated values

🐾 Swift's pattern matching capabilities are so powerful! Two enum cases with associated values can even be matched and handled by the same switch case - which is super useful when handling state changes with similar data.

``````enum DownloadState {
case inProgress(progress: Double)
case paused(progress: Double)
case cancelled
case finished(Data)
}

switch state {
case .inProgress(let progress), .paused(let progress):
updateProgressView(with: progress)
case .cancelled:
showCancelledMessage()
case .finished(let data):
process(data)
}
}
``````

## 92 Multiline string literals

🅰 One really nice benefit of Swift multiline string literals - even for single lines of text - is that they don't require quotes to be escaped. Perfect when working with things like HTML, or creating a custom description for an object.

``````let html = highlighter.highlight("Array<String>")

XCTAssertEqual(html, """
<span class="type">Array</span>&lt;<span class="type">String</span>&gt;
""")
``````

## 91 Reducing sequences

💎 While it's very common in functional programming, the `reduce` function might be a bit of a hidden gem in Swift. It provides a super useful way to transform a sequence into a single value.

``````extension Sequence where Element: Equatable {
func numberOfOccurrences(of target: Element) -> Int {
return reduce(0) { result, element in
guard element == target else {
return result
}

return result + 1
}
}
}
``````

You can read more about transforming collections in "Transforming collections in Swift".

## 90 Avoiding manual Codable implementations

📦 When I use Codable in Swift, I want to avoid manual implementations as much as possible, even when there's a mismatch between my code structure and the JSON I'm decoding.

One way that can often be achieved is to use private data containers combined with computed properties.

``````struct User: Codable {
let name: String
let age: Int

var homeTown: String { return originPlace.name }

private let originPlace: Place
}

private extension User {
struct Place: Codable {
let name: String
}
}

extension User {
struct Container: Codable {
let user: User
}
}
``````

## 89 Using feature flags instead of feature branches

🚢 Instead of using feature branches, I merge almost all of my code directly into master - and then I use feature flags to conditionally enable features when they're ready. That way I can avoid merge conflicts and keep shipping!

``````extension ListViewController {
// Rather than having to keep maintaining a separate
// feature branch for a new feature, we can use a flag
// to conditionally turn it on.
guard FeatureFlags.searchEnabled else {
return
}

let resultsVC = SearchResultsViewController()
let searchVC = UISearchController(
searchResultsController: resultsVC
)

searchVC.searchResultsUpdater = resultsVC
}
}
``````

You can read more about feature flags in "Feature flags in Swift".

## 88 Lightweight data hierarchies using tuples

💾 Here I'm using tuples to create a lightweight hierarchy for my data, giving me a nice structure without having to introduce any additional types.

``````struct CodeSegment {
var tokens: (
previous: String?,
current: String
)

var delimiters: (
previous: Character?
next: Character?
)
}

handle(segment.tokens.current)
``````

You can read more about tuples in "Using tuples as lightweight types in Swift"

## 87 The rule of threes

3️⃣ Whenever I have 3 properties or local variables that share the same prefix, I usually try to extract them into their own method or type. That way I can avoid massive types & methods, and also increase readability, without falling into a "premature optimization" trap.

Before

``````public func generate() throws {
let contentFolder = try folder.subfolder(named: "content")

let articleFolder = try contentFolder.subfolder(named: "posts")
let articleProcessor = ContentProcessor(folder: articleFolder)
let articles = try articleProcessor.process()

...
}
``````

After

``````public func generate() throws {
let contentFolder = try folder.subfolder(named: "content")
let articles = try processArticles(in: contentFolder)
...
}

private func processArticles(in folder: Folder) throws -> [ContentItem] {
let folder = try folder.subfolder(named: "posts")
let processor = ContentProcessor(folder: folder)
return try processor.process()
}
``````

## 86 Useful Codable extensions

👨‍🔧 Here's two extensions that I always add to the `Encodable` & `Decodable` protocols, which for me really make the Codable API nicer to use. By using type inference for decoding, a lot of boilerplate can be removed when the compiler is already able to infer the resulting type.

``````extension Encodable {
func encoded() throws -> Data {
return try JSONEncoder().encode(self)
}
}

extension Data {
func decoded<T: Decodable>() throws -> T {
return try JSONDecoder().decode(T.self, from: self)
}
}

let data = try user.encoded()

// By using a generic type in the decoded() method, the
// compiler can often infer the type we want to decode
// from the current context.

// And if not, we can always supply the type, still making
// the call site read very nicely.
let otherUser = try data.decoded() as User
``````

## 85 Using shared UserDefaults suites

📦 `UserDefaults` is a lot more powerful than what it first might seem like. Not only can it store more complex values (like dates & dictionaries) and parse command line arguments - it also enables easy sharing of settings & lightweight data between apps in the same App Group.

``````let sharedDefaults = UserDefaults(suiteName: "my-app-group")!
let useDarkMode = sharedDefaults.bool(forKey: "dark-mode")

// This value is put into the shared suite.
sharedDefaults.set(true, forKey: "dark-mode")

// If you want to treat the shared settings as read-only (and add
// local overrides on top of them), you can simply add the shared
// suite to the standard UserDefaults.
let combinedDefaults = UserDefaults.standard

// This value is a local override, not added to the shared suite.
combinedDefaults.set(true, forKey: "app-specific-override")
``````

## 84 Custom UIView backing layers

🎨 By overriding `layerClass` you can tell UIKit what `CALayer` class to use for a `UIView`'s backing layer. That way you can reduce the amount of layers, and don't have to do any manual layout.

``````final class GradientView: UIView {
override class var layerClass: AnyClass { return CAGradientLayer.self }

var colors: (start: UIColor, end: UIColor)? {
didSet { updateLayer() }
}

private func updateLayer() {
let layer = self.layer as! CAGradientLayer
layer.colors = colors.map { [\$0.start.cgColor, \$0.end.cgColor] }
}
}
``````

## 83 Auto-Equatable enums with associated values

✅ That the compiler now automatically synthesizes Equatable conformances is such a huge upgrade for Swift! And the cool thing is that it works for all kinds of types - even for enums with associated values! Especially useful when using enums for verification in unit tests.

``````struct Article: Equatable {
let title: String
let text: String
}

struct User: Equatable {
let name: String
let age: Int
}

extension Navigator {
enum Destination: Equatable {
case profile(User)
case article(Article)
}
}

func testNavigatingToArticle() {
let article = Article(title: "Title", text: "Text")
controller.select(article)
XCTAssertEqual(navigator.destinations, [.article(article)])
}
``````

## 82 Defaults for associated types

🤝 Associated types can have defaults in Swift - which is super useful for types that are not easily inferred (for example when they're not used for a specific instance method or property).

``````protocol Identifiable {
associatedtype RawIdentifier: Codable = String

var id: Identifier<Self> { get }
}

struct User: Identifiable {
let id: Identifier<User>
let name: String
}

struct Group: Identifiable {
typealias RawIdentifier = Int

let id: Identifier<Group>
let name: String
}
``````

## 81 Creating a dedicated identifier type

🆔 If you want to avoid using plain strings as identifiers (which can increase both type safety & readability), it's really easy to create a custom Identifier type that feels just like a native Swift type, thanks to protocols!

More on this topic in "Type-safe identifiers in Swift".

``````struct Identifier: Hashable {
let string: String
}

extension Identifier: ExpressibleByStringLiteral {
init(stringLiteral value: String) {
string = value
}
}

extension Identifier: CustomStringConvertible {
var description: String {
return string
}
}

extension Identifier: Codable {
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
string = try container.decode(String.self)
}

func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(string)
}
}

struct Article: Codable {
let id: Identifier
let title: String
}

let article = Article(id: "my-article", title: "Hello world!")
``````

## 80 Assigning optional tuple members to variables

🙌 A really cool thing about using tuples to model the internal state of a Swift type, is that you can unwrap an optional tuple's members directly into local variables.

Very useful in order to group multiple optional values together for easy unwrapping & handling.

``````class ImageTransformer {
private var queue = [(image: UIImage, transform: Transform)]()

private func processNext() {
// When unwrapping an optional tuple, you can assign the members
// directly to local variables.
guard let (image, transform) = queue.first else {
return
}

let context = Context()
context.draw(image)
context.apply(transform)
...
}
}
``````

## 79 Struct convenience initializers

❤️ I love to structure my code using extensions in Swift. One big benefit of doing so when it comes to struct initializers, is that defining a convenience initializer doesn't remove the default one the compiler generates - best of both worlds!

``````struct Article {
let date: Date
var title: String
var text: String
}

extension Article {
init(title: String, text: String) {
self.init(date: Date(), title: title, text: text, comments: [])
}
}

let articleA = Article(title: "Best Cupcake Recipe", text: "...")

let articleB = Article(
date: Date(),
title: "Best Cupcake Recipe",
text: "...",
Comment(user: currentUser, text: "Yep, can confirm!")
]
)
``````

## 78 Usages of throwing functions

🏈 A big benefit of using throwing functions for synchronous Swift APIs is that the caller can decide whether they want to treat the return value as optional (`try?`) or required (`try`).

``````func loadFile(named name: String) throws -> File {
guard let url = urlForFile(named: name) else {
throw File.Error.missing
}

do {
let data = try Data(contentsOf: url)
return File(url: url, data: data)
} catch {
throw File.Error.invalidData(error)
}
}

let requiredFile = try loadFile(named: "AppConfig.json")

let optionalFile = try? loadFile(named: "UserSettings.json")
``````

## 77 Nested generic types

🐝 Types that are nested in generics automatically inherit their parent's generic types - which is super useful when defining accessory types (for things like states or outcomes).

``````struct Task<Input, Output> {
typealias Closure = (Input) throws -> Output

let closure: Closure
}

enum Result {
case success(Output)
case failure(Error)
}
}
``````

## 76 Equatable & Hashable structures

🤖 Now that the Swift compiler automatically synthesizes Equatable & Hashable conformances for value types, it's easier than ever to setup model structures with nested types that are all `Equatable`/`Hashable`!

``````typealias Value = Hashable & Codable

struct User: Value {
var name: String
var age: Int
var settings: Settings
}

extension User {
struct Settings: Value {
var itemsPerPage: Int
var theme: Theme
}
}

extension User.Settings {
enum Theme: String, Value {
case light
case dark
}
}
``````

## 75 Conditional conformances

🎉 Swift 4.1 is here! One of the key features it brings is conditional conformances, which lets you have a type only conform to a protocol under certain constraints.

``````protocol UnboxTransformable {
associatedtype RawValue

static func transform(_ value: RawValue) throws -> Self?
}

extension Array: UnboxTransformable where Element: UnboxTransformable {
typealias RawValue = [Element.RawValue]

static func transform(_ value: RawValue) throws -> [Element]? {
return try value.compactMap(Element.transform)
}
}
``````

I also have an article with lots of more info on conditional conformances here. Paul Hudson also has a great overview of all Swift 4.1 features here.

## 74 Generic type aliases

🕵️‍♀️ A cool thing about Swift type aliases is that they can be generic! Combine that with tuples and you can easily define simple generic types.

``````typealias Pair<T> = (T, T)

extension Game {
func calculateScore(for players: Pair<Player>) -> Int {
...
}
}
``````

## 73 Parsing command line arguments using UserDefaults

☑️ A really cool "hidden" feature of UserDefaults is that it contains any arguments that were passed to the app at launch!

Super useful both in Swift command line tools & scripts, but also to temporarily override a value when debugging iOS apps.

``````let defaults = UserDefaults.standard
let query = defaults.string(forKey: "query")
let resultCount = defaults.integer(forKey: "results")
``````

## 72 Using the & operator

👏 Swift's `&` operator is awesome! Not only can you use it to compose protocols, you can compose other types too! Very useful if you want to hide concrete types & implementation details.

``````protocol LoadableFromURL {
}

...
}
}

class ViewControllerFactory {
func makeContentViewController() -> UIViewController & LoadableFromURL {
return ContentViewController()
}
}
``````

## 71 Capturing multiple values in mocks

🤗 When capturing values in mocks, using an array (instead of just a single value) makes it easy to verify that only a certain number of values were passed.

Perfect for protecting against "over-calling" something.

``````class UserManagerTests: XCTestCase {
func testObserversCalledWhenUserFirstLogsIn() {
let manager = UserManager()

let observer = ObserverMock()

// First login, observers should be notified
let user = User(id: 123, name: "John")
XCTAssertEqual(observer.users, [user])

// If the same user logs in again, observers shouldn't be notified
XCTAssertEqual(observer.users, [user])
}
}

private extension UserManagerTests {
class ObserverMock: UserManagerObserver {
private(set) var users = [User]()

func userDidChange(to user: User) {
users.append(user)
}
}
}
``````

## 70 Reducing the need for mocks

👋 When writing tests, you don't always need to create mocks - you can create stubs using real instances of things like errors, URLs & UserDefaults.

Here's how to do that for some common tasks/object types in Swift:

``````// Create errors using NSError (#function can be used to reference the name of the test)
let error = NSError(domain: #function, code: 1, userInfo: nil)

// Create non-optional URLs using file paths
let url = URL(fileURLWithPath: "Some/URL")

// Reference the test bundle using Bundle(for:)
let bundle = Bundle(for: type(of: self))

// Create an explicit UserDefaults object (instead of having to use a mock)
let userDefaults = UserDefaults(suiteName: #function)

// Create queues to control/await concurrent operations
let queue = DispatchQueue(label: #function)
``````

For when you actually do need mocking, check out "Mocking in Swift".

## 69 Using "then" as an external parameter label for closures

⏱ I've started using "then" as an external parameter label for completion handlers. Makes the call site read really nicely (Because I do ❤️ conversational API design) regardless of whether trailing closure syntax is used or not.

``````protocol DataLoader {
// Adding type aliases to protocols can be a great way to
// reduce verbosity for parameter types.
typealias Handler = (Result<Data>) -> Void
associatedtype Endpoint

func loadData(from endpoint: Endpoint, then handler: @escaping Handler)
}

...
}

...
})
``````

## 68 Combining lazily evaluated sequences with the builder pattern

😴 Combining lazily evaluated sequences with builder pattern-like properties can lead to some pretty sweet APIs for configurable sequences in Swift.

Also useful for queries & other things you "build up" and then execute.

``````// Extension adding builder pattern-like properties that return
// a new sequence value with the given configuration applied
extension FileSequence {
var recursive: FileSequence {
var sequence = self
sequence.isRecursive = true
return sequence
}

var includingHidden: FileSequence {
var sequence = self
sequence.includeHidden = true
return sequence
}
}

// BEFORE

let files = folder.makeFileSequence(recursive: true, includeHidden: true)

// AFTER

let files = folder.files.recursive.includingHidden
``````

Want an intro to lazy sequences? Check out "Swift sequences: The art of being lazy".

## 67 Faster & more stable UI tests

My top 3 tips for faster & more stable UI tests:

📱 Reset the app's state at the beginning of every test.

🆔 Use accessibility identifiers instead of UI strings.

⏱ Use expectations instead of waiting time.

``````func testOpeningArticle() {
// Launch the app with an argument that tells it to reset its state
let app = XCUIApplication()
app.launchArguments.append("--uitesting")
app.launch()

// Check that the app is displaying an activity indicator
let activityIndicator = app.activityIndicator.element
XCTAssertTrue(activityIndicator.exists)

expectation(for: NSPredicate(format: "exists == 0"),
evaluatedWith: activityIndicator)

// Use a generous timeout in case the network is slow
waitForExpectations(timeout: 10)

// Tap the cell for the first article
app.tables.cells["Article.0"].tap()

// Assert that a label with the accessibility identifier "Article.Title" exists
let label = app.staticTexts["Article.Title"]
XCTAssertTrue(label.exists)
}
``````

## 66 Accessing the clipboard from a Swift script

📋 It's super easy to access the contents of the clipboard from a Swift script. A big benefit of Swift scripting is being able to use Cocoa's powerful APIs for Mac apps.

``````import Cocoa

let clipboard = NSPasteboard.general.string(forType: .string)
``````

## 65 Using tuples for view state

🎯 Using Swift tuples for view state can be a super nice way to group multiple properties together and render them reactively using the layout system.

By using a tuple we don't have to either introduce a new type or make our view model-aware.

``````class TextView: UIView {
var state: (title: String?, text: String?) {
// By telling UIKit that our view needs layout and binding our
// state in layoutSubviews, we can react to state changes without
// doing unnecessary layout work.
didSet { setNeedsLayout() }
}

private let titleLabel = UILabel()
private let textLabel = UILabel()

override func layoutSubviews() {
super.layoutSubviews()

titleLabel.text = state.title
textLabel.text = state.text

...
}
}
``````

## 64 Throwing tests and LocalizedError

⚾️ Swift tests can throw, which is super useful in order to avoid complicated logic or force unwrapping. By making errors conform to `LocalizedError`, you can also get a nice error message in Xcode if there's a failure.

``````class ImageCacheTests: XCTestCase {
let bundle = Bundle(for: type(of: self))
let cache = ImageCache(bundle: bundle)

// bundle using this UIImage initializer
let image = try require(UIImage(named: "sample", in: bundle, compatibleWith: nil))
try cache.cache(image, forKey: "key")

let cachedImage = try cache.image(forKey: "key")
XCTAssertEqual(image, cachedImage)
}
}

enum ImageCacheError {
case emptyKey
case dataConversionFailed
}

// When using throwing tests, making your errors conform to
// LocalizedError will render a much nicer error message in
// Xcode (per default only the error code is shown).
extension ImageCacheError: LocalizedError {
var errorDescription: String? {
switch self {
case .emptyKey:
return "An empty key was given"
case .dataConversionFailed:
return "Failed to convert the given image to Data"
}
}
}
``````

For more information, and the implementation of the `require` method used above, check out "Avoiding force unwrapping in Swift unit tests".

## 63 The difference between static and class properties

✍️ Unlike `static` properties, `class` properties can be overridden by subclasses (however, they can't be stored, only computed).

``````class TableViewCell: UITableViewCell {
class var preferredHeight: CGFloat { return 60 }
}

class TallTableViewCell: TableViewCell {
override class var preferredHeight: CGFloat { return 100 }
}
``````

## 62 Creating extensions with static factory methods

👨‍🎨 Creating extensions with static factory methods can be a great alternative to subclassing in Swift, especially for things like setting up UIViews, CALayers or other kinds of styling.

It also lets you remove a lot of styling & setup from your view controllers.

``````extension UILabel {
static func makeForTitle() -> UILabel {
let label = UILabel()
label.font = .boldSystemFont(ofSize: 24)
label.textColor = .darkGray
label.minimumScaleFactor = 0.75
return label
}

static func makeForText() -> UILabel {
let label = UILabel()
label.font = .systemFont(ofSize: 16)
label.textColor = .black
label.numberOfLines = 0
return label
}
}

class ArticleViewController: UIViewController {
lazy var titleLabel = UILabel.makeForTitle()
lazy var textLabel = UILabel.makeForText()
}
``````

## 61 Child view controller auto-resizing

🧒 An awesome thing about child view controllers is that they're automatically resized to match their parent, making them a super nice solution for things like loading & error views.

``````class ListViewController: UIViewController {

self?.handle(result)
}
}
}
``````

For more about child view controller (including the `add` and `remove` methods used above), check out "Using child view controllers as plugins in Swift".

## 60 Using zip

🤐 Using the zip function in Swift you can easily combine two sequences. Super useful when using two sequences to do some work, since zip takes care of all the bounds-checking.

``````func render(titles: [String]) {
for (label, text) in zip(titleLabels, titles) {
print(text)
label.text = text
}
}
``````

## 59 Defining custom option sets

🎛 The awesome thing about option sets in Swift is that they can automatically either be passed as a single member or as a set. Even cooler is that you can easily define your own option sets as well, perfect for options and other non-exclusive values.

``````// Option sets are awesome, because you can easily pass them
// both using dot syntax and array literal syntax, like when
// using the UIView animation API:
UIView.animate(withDuration: 0.3,
delay: 0,
options: .allowUserInteraction,
animations: animations)

UIView.animate(withDuration: 0.3,
delay: 0,
options: [.allowUserInteraction, .layoutSubviews],
animations: animations)

// The cool thing is that you can easily define your own option
// sets as well, by defining a struct that has an Int rawValue,
// that will be used as a bit mask.
extension Cache {
struct Options: OptionSet {
static let saveToDisk = Options(rawValue: 1)
static let clearOnMemoryWarning = Options(rawValue: 1 << 1)
static let clearDaily = Options(rawValue: 1 << 2)

let rawValue: Int
}
}

// We can now use Cache.Options just like UIViewAnimationOptions:
Cache(options: .saveToDisk)
Cache(options: [.saveToDisk, .clearDaily])
``````

## 58 Using the where clause with associated types

🙌 Using the `where` clause when designing protocol-oriented APIs in Swift can let your implementations (or others' if it's open source) have a lot more freedom, especially when it comes to collections.

``````public protocol PathFinderMap {
associatedtype Node
// Using the 'where' clause for associated types, we can
// ensure that a type meets certain requirements (in this
// case that it's a sequence with Node elements).
associatedtype NodeSequence: Sequence where NodeSequence.Element == Node

// Instead of using a concrete type (like [Node]) here, we
// give implementors of this protocol more freedom while
// still meeting our requirements. For example, one
// implementation might use Set<Node>.
func neighbors(of node: Node) -> NodeSequence
}
``````

## 57 Using first class functions when iterating over a dictionary

👨‍🍳 Combine first class functions in Swift with the fact that Dictionary elements are (Key, Value) tuples and you can build yourself some pretty awesome functional chains when iterating over a Dictionary.

``````func makeActor(at coordinate: Coordinate, for building: Building) -> Actor {
let actor = Actor()
actor.position = coordinate.point
actor.animation = building.animation
return actor
}

func render(_ buildings: [Coordinate : Building]) {
}
``````

## 56 Calling instance methods as static functions

😎 In Swift, you can call any instance method as a static function and it will return a closure representing that method. This is how running tests using SPM on Linux works.

``````// This produces a '() -> Void' closure which is a reference to the
// given view's 'removeFromSuperview' method.
let closure = UIView.removeFromSuperview(view)

// We can now call it just like we would any other closure, and it
// will run 'view.removeFromSuperview()'
closure()

// This is how running tests using the Swift Package Manager on Linux
// works, you return your test functions as closures:
extension UserManagerTests {
static var allTests = [
("testLoggingIn", testLoggingIn),
("testLoggingOut", testLoggingOut),
("testUserPermissions", testUserPermissions)
]
}
``````

## 55 Dropping suffixes from method names to support multiple arguments

👏 One really nice benefit of dropping suffixes from method names (and just using verbs, when possible) is that it becomes super easy to support both single and multiple arguments, and it works really well semantically.

``````extension UIView {
}
}

// By dropping the "Subview" suffix from the method name, both
// single and multiple arguments work really well semantically.
``````

## 54 Constraining protocols to classes to ensure mutability

👽 Using the `AnyObject` (or `class`) constraint on protocols is not only useful when defining delegates (or other weak references), but also when you always want instances to be mutable without copying.

``````// By constraining a protocol with 'AnyObject' it can only be adopted
// by classes, which means all instances will always be mutable, and
// that it's the original instance (not a copy) that will be mutated.
protocol DataContainer: AnyObject {
var data: Data? { get set }
}

class UserSettingsManager {
private var settings: Settings
private let dataContainer: DataContainer

// Since DataContainer is a protocol, we an easily mock it in
// tests if we use dependency injection
init(settings: Settings, dataContainer: DataContainer) {
self.settings = settings
self.dataContainer = dataContainer
}

func saveSettings() throws {
let data = try settings.serialize()

// We can now assign properties on an instance of our protocol
// because the compiler knows it's always going to be a class
dataContainer.data = data
}
}
``````

## 53 String-based enums in string interpolation

🍣 Even if you define a custom raw value for a string-based enum in Swift, the full case name will be used in string interpolation.

Super useful when using separate raw values for JSON, while still wanting to use the full case name in other contexts.

``````extension Building {
// This enum has custom raw values that are used when decoding
// a value, for example from JSON.
enum Kind: String {
case castle = "C"
case town = "T"
case barracks = "B"
case goldMine = "G"
case camp = "CA"
case blacksmith = "BL"
}

var animation: Animation {
return Animation(
// When used in string interpolation, the full case name is still used.
// For 'castle' this will be 'buildings/castle'.
name: "buildings/\(kind)",
frameCount: frameCount,
frameDuration: frameDuration
)
}
}
``````

## 52 Expressively comparing a value with a list of candidates

👨‍🔬 Continuing to experiment with expressive ways of comparing a value with a list of candidates in Swift. Adding an extension on Equatable is probably my favorite approach so far.

``````extension Equatable {
func isAny(of candidates: Self...) -> Bool {
return candidates.contains(self)
}
}

let isHorizontal = direction.isAny(of: .left, .right)
``````

See tip 35 for my previous experiment.

## 51 UIView bounds and transforms

📐 A really interesting side-effect of a `UIView`'s `bounds` being its rect within its own coordinate system is that transforms don't affect it at all. That's why it's usually a better fit than `frame` when doing layout calculations of subviews.

``````let view = UIView()
view.frame.size = CGSize(width: 100, height: 100)
view.transform = CGAffineTransform(scaleX: 2, y: 2)

print(view.frame) // (-50.0, -50.0, 200.0, 200.0)
print(view.bounds) // (0.0, 0.0, 100.0, 100.0)
``````

## 50 UIKit default arguments

👏 It's awesome that many UIKit APIs with completion handlers and other optional parameters import into Swift with default arguments (even though they are written in Objective-C). Getting rid of all those nil arguments is so nice!

``````// BEFORE: All parameters are specified, just like in Objective-C

viewController.present(modalViewController, animated: true, completion: nil)

modalViewController.dismiss(animated: true, completion: nil)

to: contentViewController,
duration: 0.3,
options: [],
animations: animations,
completion: nil)

// AFTER: Since many UIKit APIs with completion handlers and other
// optional parameters import into Swift with default arguments,
// we can make our calls shorter

viewController.present(modalViewController, animated: true)

modalViewController.dismiss(animated: true)

to: contentViewController,
duration: 0.3,
animations: animations)
``````

## 49 Avoiding Massive View Controllers

✂️ Avoiding Massive View Controllers is all about finding the right levels of abstraction and splitting things up.

My personal rule of thumb is that as soon as I have 3 methods or properties that have the same prefix, I break them out into their own type.

``````// BEFORE

private lazy var signUpLabel = UILabel()
private lazy var signUpImageView = UIImageView()
private lazy var signUpButton = UIButton()
}

// AFTER

private lazy var signUpView = SignUpView()
}

class SignUpView: UIView {
private lazy var label = UILabel()
private lazy var imageView = UIImageView()
private lazy var button = UIButton()
}
``````

## 48 Extending optionals

❤️ I love the fact that optionals are enums in Swift - it makes it so easy to extend them with convenience APIs for certain types. Especially useful when doing things like data validation on optional values.

``````func validateTextFields() -> Bool {
return false
}

...

return true
}

// Since all optionals are actual enum values in Swift, we can easily
// extend them for certain types, to add our own convenience APIs

extension Optional where Wrapped == String {
var isNilOrEmpty: Bool {
switch self {
case let string?:
return string.isEmpty
case nil:
return true
}
}
}

// Since strings are now Collections in Swift 4, you can even
// add this property to all optional collections:

extension Optional where Wrapped: Collection {
var isNilOrEmpty: Bool {
switch self {
case let collection?:
return collection.isEmpty
case nil:
return true
}
}
}
``````

## 47 Using where with for-loops

🗺 Using the `where` keyword can be a super nice way to quickly apply a filter in a `for`-loop in Swift. You can of course use `map`, `filter` and `forEach`, or `guard`, but for simple loops I think this is very expressive and nice.

``````func archiveMarkedPosts() {
for post in posts where post.isMarked {
archive(post)
}
}

func healAllies() {
for player in players where player.isAllied(to: currentPlayer) {
player.heal()
}
}
``````

👻 Variable shadowing can be super useful in Swift, especially when you want to create a local copy of a parameter value in order to use it as state within a closure.

``````init(repeatMode: RepeatMode, closure: @escaping () -> UpdateOutcome) {
// Shadow the argument with a local, mutable copy
var repeatMode = repeatMode

self.closure = {
// With shadowing, there's no risk of accidentially
// referring to the immutable version
switch repeatMode {
case .forever:
break
case .times(let count):
guard count > 0 else {
return .finished
}

// We can now capture the mutable version and use
// it for state in a closure
repeatMode = .times(count - 1)
}

return closure()
}
}
``````

## 45 Using dot syntax for static properties and initializers

✒️ Dot syntax is one of my favorite features of Swift. What's really cool is that it's not only for enums, any static method or property can be used with dot syntax - even initializers! Perfect for convenience APIs and default parameters.

``````public enum RepeatMode {
case times(Int)
case forever
}

public extension RepeatMode {
static var never: RepeatMode {
return .times(0)
}

static var once: RepeatMode {
return .times(1)
}
}

view.perform(animation, repeated: .once)

// To make default parameters more compact, you can even use init with dot syntax

init(cache: Cache = .init(), decoder: ImageDecoder = .init()) {
...
}
}
``````

## 44 Calling functions as closures with a tuple as parameters

🚀 One really cool aspect of Swift having first class functions is that you can pass any function (or even initializer) as a closure, and even call it with a tuple containing its parameters!

``````// This function lets us treat any "normal" function or method as
// a closure and run it with a tuple that contains its parameters
func call<Input, Output>(_ function: (Input) -> Output, with input: Input) -> Output {
return function(input)
}

class ViewFactory {
// We can now pass an initializer as a closure, and a tuple
// containing its parameters
}

private func loadTextStyles() -> (font: UIFont, color: UIColor) {
return (theme.font, theme.textColor)
}
}

init(font: UIFont, textColor: UIColor) {
...
}
}
``````

## 43 Enabling static dependency injection

💉 If you've been struggling to test code that uses static APIs, here's a technique you can use to enable static dependency injection without having to modify any call sites:

``````// Before: Almost impossible to test due to the use of singletons

class Analytics {
static func log(_ event: Event) {
Database.shared.save(event)

let dictionary = event.serialize()
NetworkManager.shared.post(dictionary, to: eventURL)
}
}

// After: Much easier to test, since we can inject mocks as arguments

class Analytics {
static func log(_ event: Event,
database: Database = .shared,
networkManager: NetworkManager = .shared) {
database.save(event)

let dictionary = event.serialize()
networkManager.post(dictionary, to: eventURL)
}
}
``````

## 42 Type inference for lazy properties in Swift 4

🎉 In Swift 4, type inference works for lazy properties and you don't need to explicitly refer to `self`!

``````// Swift 3

class PurchaseView: UIView {

private func makeBuyButton() -> UIButton {
let button = UIButton()
button.setTitleColor(.blue, for: .normal)
return button
}
}

// Swift 4

class PurchaseView: UIView {

private func makeBuyButton() -> UIButton {
let button = UIButton()
button.setTitleColor(.blue, for: .normal)
return button
}
}
``````

## 41 Converting Swift errors to NSError

😎 You can turn any Swift `Error` into an `NSError`, which is super useful when pattern matching with a code 👍. Also, switching on optionals is pretty cool!

``````let task = urlSession.dataTask(with: url) { data, _, error in
switch error {
case .some(let error as NSError) where error.code == NSURLErrorNotConnectedToInternet:
presenter.showOfflineView()
case .some(let error):
presenter.showGenericErrorView()
case .none:
presenter.renderContent(from: data)
}
}

``````

Also make sure to check out Kostas Kremizas' tip about how you can pattern match directly against a member of `URLError`.

## 40 Making UIImage macOS compatible

🖥 Here's an easy way to make iOS model code that uses `UIImage` macOS compatible - like me and Gui Rambo discussed on the Swift by Sundell Podcast.

``````// Either put this in a separate file that you only include in your macOS target or wrap the code in #if os(macOS) / #endif

import Cocoa

// Step 1: Typealias UIImage to NSImage
typealias UIImage = NSImage

// Step 2: You might want to add these APIs that UIImage has but NSImage doesn't.
extension NSImage {
var cgImage: CGImage? {
var proposedRect = CGRect(origin: .zero, size: size)

return cgImage(forProposedRect: &proposedRect,
context: nil,
hints: nil)
}

convenience init?(named name: String) {
self.init(named: Name(name))
}
}

// Step 3: Profit - you can now make your model code that uses UIImage cross-platform!
struct User {
let name: String
let profileImage: UIImage
}
``````

## 39 Internally mutable protocol-oriented APIs

🤖 You can easily define a protocol-oriented API that can only be mutated internally, by using an internal protocol that extends a public one.

``````// Declare a public protocol that acts as your immutable API
public protocol ModelHolder {
associatedtype Model
var model: Model { get }
}

// Declare an extended, internal protocol that provides a mutable API
internal protocol MutableModelHolder: ModelHolder {
var model: Model { get set }
}

// You can now implement the requirements using 'public internal(set)'
public class UserHolder: MutableModelHolder {
public internal(set) var model: User

internal init(model: User) {
self.model = model
}
}
``````

## 38 Switching on a set

🎛 You can switch on a set using array literals as cases in Swift! Can be really useful to avoid many `if`/`else if` statements.

``````class RoadTile: Tile {
var connectedDirections = Set<Direction>()

func render() {
switch connectedDirections {
case [.up, .down]:
case [.left, .right]:
default:
}
}
}
``````

## 37 Adding the current locale to cache keys

🌍 When caching localized content in an app, it's a good idea to add the current locale to all keys, to prevent bugs when switching languages.

``````func cache(_ content: Content, forKey key: String) throws {
let data = try wrap(content) as Data
let key = localize(key: key)
try storage.store(data, forKey: key)
}

func loadCachedContent(forKey key: String) -> Content? {
let key = localize(key: key)
return data.flatMap { try? unbox(data: \$0) }
}

private func localize(key: String) -> String {
return key + "-" + Bundle.main.preferredLocalizations[0]
}
``````

## 36 Setting up tests to avoid retain cycles with weak references

🚳 Here's an easy way to setup a test to avoid accidental retain cycles with object relationships (like weak delegates & observers) in Swift:

``````func testDelegateNotRetained() {
// Assign the delegate (weak) and also retain it using a local var
var delegate: Delegate? = DelegateMock()
controller.delegate = delegate
XCTAssertNotNil(controller.delegate)

// Release the local var, which should also release the weak reference
delegate = nil
XCTAssertNil(controller.delegate)
}
``````

## 35 Expressively matching a value against a list of candidates

👨‍🔬 Playing around with an expressive way to check if a value matches any of a list of candidates in Swift:

``````// Instead of multiple conditions like this:

if string == "One" || string == "Two" || string == "Three" {

}

// You can now do:

if string == any(of: "One", "Two", "Three") {

}
``````

You can find a gist with the implementation here.

## 34 Organizing code using extensions

👪 APIs in a Swift extension automatically inherit its access control level, making it a neat way to organize public, internal & private APIs.

``````public extension Animation {
init(textureNamed textureName: String) {
frames = [Texture(name: textureName)]
}

init(texturesNamed textureNames: [String], frameDuration: TimeInterval = 1) {
frames = textureNames.map(Texture.init)
self.frameDuration = frameDuration
}

init(image: Image) {
frames = [Texture(image: image)]
}
}

internal extension Animation {
}
}
``````

## 33 Using map to transform an optional into a Result type

🗺 Using `map` you can transform an optional value into an optional `Result` type by simply passing in the enum case.

``````enum Result<Value> {
case value(Value)
case error(Error)
}

class Promise<Value> {
private var result: Result<Value>?

init(value: Value? = nil) {
result = value.map(Result.value)
}
}
``````

## 32 Assigning to self in struct initializers

👌 It's so nice that you can assign directly to `self` in `struct` initializers in Swift. Very useful when adding conformance to protocols.

``````extension Bool: AnswerConvertible {
public init(input: String) throws {
switch input.lowercased() {
case "y", "yes", "👍":
self = true
default:
self = false
}
}
}
``````

## 31 Recursively calling closures as inline functions

☎️ Defining Swift closures as inline functions enables you to recursively call them, which is super useful in things like custom sequences.

``````class Database {
func records(matching query: Query) -> AnySequence<Record> {

func iterate() -> Record? {
guard let nextRecord = recordIterator.next() else {
return nil
}

guard nextRecord.matches(query) else {
// Since the closure is an inline function, it can be recursively called,
// in this case in order to advance to the next item.
return iterate()
}

return nextRecord
}

// AnySequence/AnyIterator are part of the standard library and provide an easy way
// to define custom sequences using closures.
return AnySequence { AnyIterator(iterate) }
}
}
``````

Rob Napier points out that using the above might cause crashes if used on a large databaset, since Swift has no guaranteed Tail Call Optimization (TCO).

Slava Pestov also points out that another benefit of inline functions vs closures is that they can have their own generic parameter list.

## 30 Passing self to required Objective-C dependencies

🏖 Using lazy properties in Swift, you can pass `self` to required Objective-C dependencies without having to use force-unwrapped optionals.

``````class DataLoader: NSObject {
lazy var urlSession: URLSession = self.makeURLSession()

private func makeURLSession() -> URLSession {
return URLSession(configuration: .default, delegate: self, delegateQueue: .main)
}
}

class Renderer {

}
}
``````

## 29 Making weak or lazy properties readonly

👓 If you have a property in Swift that needs to be `weak` or `lazy`, you can still make it readonly by using `private(set)`.

``````class Node {
private(set) weak var parent: Node?
private(set) lazy var children = [Node]()

children.append(child)
child.parent = self
}
}
``````

## 28 Defining static URLs using string literals

🌏 Tired of using `URL(string: "url")!` for static URLs? Make `URL` conform to `ExpressibleByStringLiteral` and you can now simply use `"url"` instead.

``````extension URL: ExpressibleByStringLiteral {
// By using 'StaticString' we disable string interpolation, for safety
public init(stringLiteral value: StaticString) {
self = URL(string: "\(value)").require(hint: "Invalid URL string literal: \(value)")
}
}

// We can now define URLs using static string literals 🎉
let url: URL = "https://www.swiftbysundell.com"

// In Swift 3 or earlier, you also have to implement 2 additional initializers
extension URL {
public init(extendedGraphemeClusterLiteral value: StaticString) {
self.init(stringLiteral: value)
}

public init(unicodeScalarLiteral value: StaticString) {
self.init(stringLiteral: value)
}
}
``````

To find the extension that adds the `require()` method on `Optional` that I use above, check out Require.

## 27 Manipulating points, sizes and frames using math operators

✚ I'm always careful with operator overloading, but for manipulating things like sizes, points & frames I find them super useful.

``````extension CGSize {
static func *(lhs: CGSize, rhs: CGFloat) -> CGSize {
return CGSize(width: lhs.width * rhs, height: lhs.height * rhs)
}
}

button.frame.size = image.size * 2
``````

If you like the above idea, check out CGOperators, which contains math operator overloads for all Core Graphics' vector types.

## 26 Using closure types in generic constraints

🔗 You can use closure types in generic constraints in Swift. Enables nice APIs for handling sequences of closures.

``````extension Sequence where Element == () -> Void {
func callAll() {
forEach { \$0() }
}
}

extension Sequence where Element == () -> String {
func joinedResults(separator: String) -> String {
return map { \$0() }.joined(separator: separator)
}
}

callbacks.callAll()
let names = nameProviders.joinedResults(separator: ", ")
``````

(If you're using Swift 3, you have to change `Element` to `Iterator.Element`)

## 25 Using associated enum values to avoid state-specific optionals

🎉 Using associated enum values is a super nice way to encapsulate mutually exclusive state info (and avoiding state-specific optionals).

``````// BEFORE: Lots of state-specific, optional properties

class Player {
var isWaitingForMatchMaking: Bool
var invitingUser: User?
var numberOfLives: Int
var playerDefeatedBy: Player?
var roundDefeatedIn: Int?
}

// AFTER: All state-specific information is encapsulated in enum cases

class Player {
enum State {
case waitingForMatchMaking
case waitingForInviteResponse(from: User)
case active(numberOfLives: Int)
case defeated(by: Player, roundNumber: Int)
}

var state: State
}
``````

## 24 Using enums for async result types

👍 I really like using enums for all async result types, even boolean ones. Self-documenting, and makes the call site a lot nicer to read too!

``````protocol PushNotificationService {
// Before
func enablePushNotifications(completionHandler: @escaping (Bool) -> Void)

// After
}

case enabled
case disabled
}

if status == .enabled {
}
}
``````

## 23 Working on async code in a playground

🏃 Want to work on your async code in a Swift Playground? Just set `needsIndefiniteExecution` to true to keep it running:

``````import PlaygroundSupport

PlaygroundPage.current.needsIndefiniteExecution = true

let greeting = "Hello after 3 seconds"
print(greeting)
}
``````

To stop the playground from executing, simply call `PlaygroundPage.current.finishExecution()`.

## 22 Overriding self with a weak reference

💦 Avoid memory leaks when accidentially refering to `self` in closures by overriding it locally with a weak reference:

Swift >= 4.2

``````dataLoader.loadData(from: url) { [weak self] result in
guard let self = self else {
return
}

self.cache(result)

...
``````

Swift < 4.2

``````dataLoader.loadData(from: url) { [weak self] result in
guard let `self` = self else {
return
}

self.cache(result)

...
``````

Note that the reason the above currently works is because of a compiler bug (which I hope gets turned into a properly supported feature soon).

## 21 Using DispatchWorkItem

🕓 Using dispatch work items you can easily cancel a delayed asynchronous GCD task if you no longer need it:

``````let workItem = DispatchWorkItem {
// Your async code goes in here
}

// Execute the work item after 1 second
DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: workItem)

// You can cancel the work item if you no longer need it
workItem.cancel()
``````

## 20 Combining a sequence of functions

➕ While working on a new Swift developer tool (to be open sourced soon 😉), I came up with a pretty neat way of organizing its sequence of operations, by combining their functions into a closure:

``````internal func +<A, B, C>(lhs: @escaping (A) throws -> B,
rhs: @escaping (B) throws -> C) -> (A) throws -> C {
return { try rhs(lhs(\$0)) }
}

public func run() throws {
try (determineTarget + build + analyze + output)()
}
``````

If you're familiar with the functional programming world, you might know the above technique as the pipe operator (thanks to Alexey Demedreckiy for pointing this out!)

## 19 Chaining optionals with map() and flatMap()

🗺 Using `map()` and `flatMap()` on optionals you can chain multiple operations without having to use lengthy `if lets` or `guards`:

``````// BEFORE

guard let string = argument(at: 1) else {
return
}

guard let url = URL(string: string) else {
return
}

handle(url)

// AFTER

argument(at: 1).flatMap(URL.init).map(handle)
``````

## 18 Using self-executing closures for lazy properties

🚀 Using self-executing closures is a great way to encapsulate lazy property initialization:

``````class StoreViewController: UIViewController {
private lazy var collectionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
let view = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout)
view.delegate = self
view.dataSource = self
return view
}()

}
}
``````

## 17 Speeding up Swift package tests

⚡️ You can speed up your Swift package tests using the `--parallel` flag. For Marathon, the tests execute 3 times faster that way!

``````swift test --parallel
``````

## 16 Avoiding mocking UserDefaults

🛠 Struggling with mocking `UserDefaults` in a test? The good news is: you don't need mocking - just create a real instance:

``````class LoginTests: XCTestCase {
private var userDefaults: UserDefaults!

override func setUp() {
super.setup()

userDefaults = UserDefaults(suiteName: #file)
userDefaults.removePersistentDomain(forName: #file)

}
}
``````

👍 Using variadic parameters in Swift, you can create some really nice APIs that take a list of objects without having to use an array:

``````extension Canvas {
}
}

let circle = Circle(center: CGPoint(x: 5, y: 5), radius: 5)
let lineA = Line(start: .zero, end: CGPoint(x: 10, y: 10))
let lineB = Line(start: CGPoint(x: 0, y: 10), end: CGPoint(x: 10, y: 0))

let canvas = Canvas()
canvas.render()
``````

## 14 Referring to enum cases with associated values as closures

😮 Just like you can refer to a Swift function as a closure, you can do the same thing with enum cases with associated values:

``````enum UnboxPath {
case key(String)
case keyPath(String)
}

struct UserSchema {
static let name = key("name")
static let age = key("age")
static let posts = key("posts")

private static let key = UnboxPath.key
}
``````

## 13 Using the === operator to compare objects by instance

📈 The `===` operator lets you check if two objects are the same instance. Very useful when verifying that an array contains an instance in a test:

``````protocol InstanceEquatable: class, Equatable {}

extension InstanceEquatable {
static func ==(lhs: Self, rhs: Self) -> Bool {
return lhs === rhs
}
}

extension Enemy: InstanceEquatable {}

func testDestroyingEnemy() {
player.attack(enemy)
XCTAssertTrue(player.destroyedEnemies.contains(enemy))
}
``````

## 12 Calling initializers with dot syntax and passing them as closures

😎 Cool thing about Swift initializers: you can call them using dot syntax and pass them as closures! Perfect for mocking dates in tests.

``````class Logger {
private let storage: LogStorage
private let dateProvider: () -> Date

init(storage: LogStorage = .init(), dateProvider: @escaping () -> Date = Date.init) {
self.storage = storage
self.dateProvider = dateProvider
}

func log(event: Event) {
storage.store(event: event, date: dateProvider())
}
}
``````

## 11 Structuring UI tests as extensions on XCUIApplication

📱 Most of my UI testing logic is now categories on `XCUIApplication`. Makes the test cases really easy to read:

``````func testLoggingInAndOut() {
XCTAssertFalse(app.userIsLoggedIn)

app.launch()
XCTAssertTrue(app.userIsLoggedIn)

app.logout()
XCTAssertFalse(app.userIsLoggedIn)
}

func testDisplayingCategories() {
XCTAssertFalse(app.isDisplayingCategories)

app.launch()
app.goToCategories()
XCTAssertTrue(app.isDisplayingCategories)
}
``````

## 10 Avoiding default cases in switch statements

🙂 It’s a good idea to avoid “default” cases when switching on Swift enums - it’ll “force you” to update your logic when a new case is added:

``````enum State {
case loggedIn
case loggedOut
case onboarding
}

func handle(_ state: State) {
switch state {
case .loggedIn:
showMainUI()
case .loggedOut:
// Compiler error: Switch must be exhaustive
}
}
``````

## 9 Using the guard statement in many different scopes

💂 It's really cool that you can use Swift's 'guard' statement to exit out of pretty much any scope, not only return from functions:

``````// You can use the 'guard' statement to...

for string in strings {
// ...continue an iteration
guard shouldProcess(string) else {
continue
}

// ...or break it
guard !shouldBreak(for: string) else {
break
}

// ...or return
guard !shouldReturn(for: string) else {
return
}

// ..or throw an error
guard string.isValid else {
throw StringError.invalid(string)
}

// ...or exit the program
guard !shouldExit(for: string) else {
exit(1)
}
}
``````

## 8 Passing functions & operators as closures

❤️ Love how you can pass functions & operators as closures in Swift. For example, it makes the syntax for sorting arrays really nice!

``````let array = [3, 9, 1, 4, 6, 2]
let sorted = array.sorted(by: <)
``````

## 7 Using #function for UserDefaults key consistency

🗝 Here's a neat little trick I use to get UserDefault key consistency in Swift (#function expands to the property name in getters/setters). Just remember to write a good suite of tests that'll guard you against bugs when changing property names.

``````extension UserDefaults {
var onboardingCompleted: Bool {
get { return bool(forKey: #function) }
set { set(newValue, forKey: #function) }
}
}
``````

## 6 Using a name already taken by the standard library

📛 Want to use a name already taken by the standard library for a nested type? No problem - just use `Swift.` to disambiguate:

``````extension Command {
enum Error: Swift.Error {
case missing
case invalid(String)
}
}
``````

## 5 Using Wrap to implement Equatable

📦 Playing around with using Wrap to implement `Equatable` for any type, primarily for testing:

``````protocol AutoEquatable: Equatable {}

extension AutoEquatable {
static func ==(lhs: Self, rhs: Self) -> Bool {
let lhsData = try! wrap(lhs) as Data
let rhsData = try! wrap(rhs) as Data
return lhsData == rhsData
}
}
``````

## 4 Using typealiases to reduce the length of method signatures

📏 One thing that I find really useful in Swift is to use typealiases to reduce the length of method signatures in generic types:

``````public class PathFinder<Object: PathFinderObject> {
public typealias Map = Object.Map
public typealias Node = Map.Node
public typealias Path = PathFinderPath<Object>

public static func possiblePaths(for object: Object, at rootNode: Node, on map: Map) -> Path.Sequence {
return .init(object: object, rootNode: rootNode, map: map)
}
}
``````

## 3 Referencing either external or internal parameter name when writing docs

📖 You can reference either the external or internal parameter label when writing Swift docs - and they get parsed the same:

``````// EITHER:

class Foo {
/**
*   - parameter string: A string
*/
func bar(with string: String) {}
}

// OR:

class Foo {
/**
*   - parameter with: A string
*/
func bar(with string: String) {}
}
``````

## 2 Using auto closures

👍 Finding more and more uses for auto closures in Swift. Can enable some pretty nice APIs:

``````extension Dictionary {
mutating func value(for key: Key, orAdd valueClosure: @autoclosure () -> Value) -> Value {
if let value = self[key] {
return value
}

let value = valueClosure()
self[key] = value
return value
}
}
``````

## 1 Namespacing with nested types

🚀 I’ve started to become a really big fan of nested types in Swift. Love the additional namespacing it gives you!

``````public struct Map {
public struct Model {
public let size: Size
public let theme: Theme
public var terrain: [Position : Terrain.Model]
public var units: [Position : Unit.Model]
public var buildings: [Position : Building.Model]
}

public enum Direction {
case up
case right
case down
case left
}

public struct Position {
public var x: Int
public var y: Int
}

public enum Size: String {
case small = "S"
case medium = "M"
case large = "L"
case extraLarge = "XL"
}
}``````

Author: JohnSundell
Source Code: https://github.com/JohnSundell/SwiftTips

1661592007

## A Collection Of Swift Tips & Tricks That I've Shared on Twitter

⚠️ This list is no longer being updated. For my latest Swift tips, checkout the "Tips" section on Swift by Sundell.

## Swift tips & tricks ⚡️

One of the things I really love about Swift is how I keep finding interesting ways to use it in various situations, and when I do - I usually share them on Twitter. Here's a collection of all the tips & tricks that I've shared so far. Each entry has a link to the original tweet, if you want to respond with some feedback or question, which is always super welcome! 🚀

Also make sure to check out all of my other Swift content:

## #102 Making async tests faster and more stable

🚀 Here are some quick tips to make async tests faster & more stable:

• 😴 Avoid sleep() - use expectations instead
• ⏱ Use generous timeouts to avoid flakiness on CI
• 🧐 Put all assertions at the end of each test, not inside closures
``````// BEFORE:

class MentionDetectorTests: XCTestCase {
func testDetectingMention() {
let detector = MentionDetector()
let string = "This test was written by @johnsundell."

detector.detectMentions(in: string) { mentions in
XCTAssertEqual(mentions, ["johnsundell"])
}

sleep(2)
}
}

// AFTER:

class MentionDetectorTests: XCTestCase {
func testDetectingMention() {
let detector = MentionDetector()
let string = "This test was written by @johnsundell."

var mentions: [String]?
let expectation = self.expectation(description: #function)

detector.detectMentions(in: string) {
mentions = \$0
expectation.fulfill()
}

waitForExpectations(timeout: 10)
XCTAssertEqual(mentions, ["johnsundell"])
}
}
``````

For more on async testing, check out "Unit testing asynchronous Swift code".

## #101 Adding support for Apple Pencil double-taps

✍️ Adding support for the new Apple Pencil double-tap feature is super easy! All you have to do is to create a `UIPencilInteraction`, add it to a view, and implement one delegate method. Hopefully all pencil-compatible apps will soon adopt this.

``````let interaction = UIPencilInteraction()
interaction.delegate = self

extension ViewController: UIPencilInteractionDelegate {
func pencilInteractionDidTap(_ interaction: UIPencilInteraction) {
// Handle pencil double-tap
}
}
``````

For more on using this and other iPad Pro features, check out "Building iPad Pro features in Swift".

## #100 Combining values with functions

😎 Here's a cool function that combines a value with a function to return a closure that captures that value, so that it can be called without any arguments. Super useful when working with closure-based APIs and we want to use some of our properties without having to capture `self`.

``````func combine<A, B>(_ value: A, with closure: @escaping (A) -> B) -> () -> B {
return { closure(value) }
}

// BEFORE:

class ProductViewController: UIViewController {

buyButton.handler = { [weak self] in
guard let self = self else {
return
}

self.productManager.startCheckout(for: self.product)
}
}
}

// AFTER:

class ProductViewController: UIViewController {

}
}
``````

## #99 Dependency injection using functions

💉 When I'm only using a single function from a dependency, I love to inject that function as a closure, instead of having to create a protocol and inject the whole object. Makes dependency injection & testing super simple.

``````final class ArticleLoader {
typealias Networking = (Endpoint) -> Future<Data>

private let networking: Networking

init(networking: @escaping Networking = URLSession.shared.load) {
self.networking = networking
}

return networking(.latestArticles).decode()
}
}
``````

For more on this technique, check out "Simple Swift dependency injection with functions".

## #98 Using a custom exception handler

💥 It's cool that you can easily assign a closure as a custom `NSException` handler. This is super useful when building things in Playgrounds - since you can't use breakpoints - so instead of just `signal SIGABRT`, you'll get the full exception description if something goes wrong.

``````NSSetUncaughtExceptionHandler { exception in
print(exception)
}
``````

## #97 Using type aliases to give semantic meaning to primitives

❤️ I love that in Swift, we can use the type system to make our code so much more self-documenting - one way of doing so is to use type aliases to give the primitive types that we use a more semantic meaning.

``````extension List.Item {
// Using type aliases, we can give semantic meaning to the
// primitive types that we use, without having to introduce
// wrapper types.
typealias Index = Int
}

extension List {
enum Mutation {
// Our enum cases now become a lot more self-documenting,
// explain them.
case update(Item, Item.Index)
case remove(Item.Index)
}
}
``````

For more on self-documenting code, check out "Writing self-documenting Swift code".

## #96 Specializing protocols using constraints

🤯 A little late night prototyping session reveals that protocol constraints can not only be applied to extensions - they can also be added to protocol definitions!

This is awesome, since it lets us easily define specialized protocols based on more generic ones.

``````protocol Component {
associatedtype Container
}

// Protocols that inherit from other protocols can include
// constraints to further specialize them.
protocol ViewComponent: Component where Container == UIView {
associatedtype View: UIView
var view: View { get }
}

extension ViewComponent {
}
}
``````

For more on specializing protocols, check out "Specializing protocols in Swift".

## #95 Unwrapping an optional or throwing an error

📦 Here's a super handy extension on Swift's `Optional` type, which gives us a really nice API for easily unwrapping an optional, or throwing an error in case the value turned out to be `nil`:

``````extension Optional {
func orThrow(_ errorExpression: @autoclosure () -> Error) throws -> Wrapped {
switch self {
case .some(let value):
return value
case .none:
throw errorExpression()
}
}
}

let file = try loadFile(at: path).orThrow(MissingFileError())
``````

For more ways that optionals can be extended, check out "Extending optionals in Swift".

## #94 Testing code that uses static APIs

👩‍🔬 Testing code that uses static APIs can be really tricky, but there's a way that it can often be done - using Swift's first class function capabilities!

Instead of accessing that static API directly, we can inject the function we want to use, which enables us to mock it!

``````// BEFORE

func loadFriends(then handler: @escaping (Result<[Friend]>) -> Void) {
...
}
}
}

// AFTER

typealias Handler<T> = (Result<T>) -> Void

then handler: @escaping Handler<[Friend]>) {
...
}
}
}

// MOCKING IN TESTS

handler(.success(mockData))
}

...
}
``````

## #93 Matching multiple enum cases with associated values

🐾 Swift's pattern matching capabilities are so powerful! Two enum cases with associated values can even be matched and handled by the same switch case - which is super useful when handling state changes with similar data.

``````enum DownloadState {
case inProgress(progress: Double)
case paused(progress: Double)
case cancelled
case finished(Data)
}

switch state {
case .inProgress(let progress), .paused(let progress):
updateProgressView(with: progress)
case .cancelled:
showCancelledMessage()
case .finished(let data):
process(data)
}
}
``````

## #92 Multiline string literals

🅰 One really nice benefit of Swift multiline string literals - even for single lines of text - is that they don't require quotes to be escaped. Perfect when working with things like HTML, or creating a custom description for an object.

``````let html = highlighter.highlight("Array<String>")

XCTAssertEqual(html, """
<span class="type">Array</span>&lt;<span class="type">String</span>&gt;
""")
``````

## #91 Reducing sequences

💎 While it's very common in functional programming, the `reduce` function might be a bit of a hidden gem in Swift. It provides a super useful way to transform a sequence into a single value.

``````extension Sequence where Element: Equatable {
func numberOfOccurrences(of target: Element) -> Int {
return reduce(0) { result, element in
guard element == target else {
return result
}

return result + 1
}
}
}
``````

You can read more about transforming collections in "Transforming collections in Swift".

## #90 Avoiding manual Codable implementations

📦 When I use Codable in Swift, I want to avoid manual implementations as much as possible, even when there's a mismatch between my code structure and the JSON I'm decoding.

One way that can often be achieved is to use private data containers combined with computed properties.

``````struct User: Codable {
let name: String
let age: Int

var homeTown: String { return originPlace.name }

private let originPlace: Place
}

private extension User {
struct Place: Codable {
let name: String
}
}

extension User {
struct Container: Codable {
let user: User
}
}
``````

## #89 Using feature flags instead of feature branches

🚢 Instead of using feature branches, I merge almost all of my code directly into master - and then I use feature flags to conditionally enable features when they're ready. That way I can avoid merge conflicts and keep shipping!

``````extension ListViewController {
// Rather than having to keep maintaining a separate
// feature branch for a new feature, we can use a flag
// to conditionally turn it on.
guard FeatureFlags.searchEnabled else {
return
}

let resultsVC = SearchResultsViewController()
let searchVC = UISearchController(
searchResultsController: resultsVC
)

searchVC.searchResultsUpdater = resultsVC
}
}
``````

You can read more about feature flags in "Feature flags in Swift".

## #88 Lightweight data hierarchies using tuples

💾 Here I'm using tuples to create a lightweight hierarchy for my data, giving me a nice structure without having to introduce any additional types.

``````struct CodeSegment {
var tokens: (
previous: String?,
current: String
)

var delimiters: (
previous: Character?
next: Character?
)
}

handle(segment.tokens.current)
``````

You can read more about tuples in "Using tuples as lightweight types in Swift"

## #87 The rule of threes

3️⃣ Whenever I have 3 properties or local variables that share the same prefix, I usually try to extract them into their own method or type. That way I can avoid massive types & methods, and also increase readability, without falling into a "premature optimization" trap.

Before

``````public func generate() throws {
let contentFolder = try folder.subfolder(named: "content")

let articleFolder = try contentFolder.subfolder(named: "posts")
let articleProcessor = ContentProcessor(folder: articleFolder)
let articles = try articleProcessor.process()

...
}
``````

After

``````public func generate() throws {
let contentFolder = try folder.subfolder(named: "content")
let articles = try processArticles(in: contentFolder)
...
}

private func processArticles(in folder: Folder) throws -> [ContentItem] {
let folder = try folder.subfolder(named: "posts")
let processor = ContentProcessor(folder: folder)
return try processor.process()
}
``````

## #86 Useful Codable extensions

👨‍🔧 Here's two extensions that I always add to the `Encodable` & `Decodable` protocols, which for me really make the Codable API nicer to use. By using type inference for decoding, a lot of boilerplate can be removed when the compiler is already able to infer the resulting type.

``````extension Encodable {
func encoded() throws -> Data {
return try JSONEncoder().encode(self)
}
}

extension Data {
func decoded<T: Decodable>() throws -> T {
return try JSONDecoder().decode(T.self, from: self)
}
}

let data = try user.encoded()

// By using a generic type in the decoded() method, the
// compiler can often infer the type we want to decode
// from the current context.

// And if not, we can always supply the type, still making
// the call site read very nicely.
let otherUser = try data.decoded() as User
``````

## #85 Using shared UserDefaults suites

📦 `UserDefaults` is a lot more powerful than what it first might seem like. Not only can it store more complex values (like dates & dictionaries) and parse command line arguments - it also enables easy sharing of settings & lightweight data between apps in the same App Group.

``````let sharedDefaults = UserDefaults(suiteName: "my-app-group")!
let useDarkMode = sharedDefaults.bool(forKey: "dark-mode")

// This value is put into the shared suite.
sharedDefaults.set(true, forKey: "dark-mode")

// If you want to treat the shared settings as read-only (and add
// local overrides on top of them), you can simply add the shared
// suite to the standard UserDefaults.
let combinedDefaults = UserDefaults.standard

// This value is a local override, not added to the shared suite.
combinedDefaults.set(true, forKey: "app-specific-override")
``````

## #84 Custom UIView backing layers

🎨 By overriding `layerClass` you can tell UIKit what `CALayer` class to use for a `UIView`'s backing layer. That way you can reduce the amount of layers, and don't have to do any manual layout.

``````final class GradientView: UIView {
override class var layerClass: AnyClass { return CAGradientLayer.self }

var colors: (start: UIColor, end: UIColor)? {
didSet { updateLayer() }
}

private func updateLayer() {
let layer = self.layer as! CAGradientLayer
layer.colors = colors.map { [\$0.start.cgColor, \$0.end.cgColor] }
}
}
``````

## #83 Auto-Equatable enums with associated values

✅ That the compiler now automatically synthesizes Equatable conformances is such a huge upgrade for Swift! And the cool thing is that it works for all kinds of types - even for enums with associated values! Especially useful when using enums for verification in unit tests.

``````struct Article: Equatable {
let title: String
let text: String
}

struct User: Equatable {
let name: String
let age: Int
}

extension Navigator {
enum Destination: Equatable {
case profile(User)
case article(Article)
}
}

func testNavigatingToArticle() {
let article = Article(title: "Title", text: "Text")
controller.select(article)
XCTAssertEqual(navigator.destinations, [.article(article)])
}
``````

## #82 Defaults for associated types

🤝 Associated types can have defaults in Swift - which is super useful for types that are not easily inferred (for example when they're not used for a specific instance method or property).

``````protocol Identifiable {
associatedtype RawIdentifier: Codable = String

var id: Identifier<Self> { get }
}

struct User: Identifiable {
let id: Identifier<User>
let name: String
}

struct Group: Identifiable {
typealias RawIdentifier = Int

let id: Identifier<Group>
let name: String
}
``````

## #81 Creating a dedicated identifier type

🆔 If you want to avoid using plain strings as identifiers (which can increase both type safety & readability), it's really easy to create a custom Identifier type that feels just like a native Swift type, thanks to protocols!

More on this topic in "Type-safe identifiers in Swift".

``````struct Identifier: Hashable {
let string: String
}

extension Identifier: ExpressibleByStringLiteral {
init(stringLiteral value: String) {
string = value
}
}

extension Identifier: CustomStringConvertible {
var description: String {
return string
}
}

extension Identifier: Codable {
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
string = try container.decode(String.self)
}

func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(string)
}
}

struct Article: Codable {
let id: Identifier
let title: String
}

let article = Article(id: "my-article", title: "Hello world!")
``````

## #80 Assigning optional tuple members to variables

🙌 A really cool thing about using tuples to model the internal state of a Swift type, is that you can unwrap an optional tuple's members directly into local variables.

Very useful in order to group multiple optional values together for easy unwrapping & handling.

``````class ImageTransformer {
private var queue = [(image: UIImage, transform: Transform)]()

private func processNext() {
// When unwrapping an optional tuple, you can assign the members
// directly to local variables.
guard let (image, transform) = queue.first else {
return
}

let context = Context()
context.draw(image)
context.apply(transform)
...
}
}
``````

## #79 Struct convenience initializers

❤️ I love to structure my code using extensions in Swift. One big benefit of doing so when it comes to struct initializers, is that defining a convenience initializer doesn't remove the default one the compiler generates - best of both worlds!

``````struct Article {
let date: Date
var title: String
var text: String
}

extension Article {
init(title: String, text: String) {
self.init(date: Date(), title: title, text: text, comments: [])
}
}

let articleA = Article(title: "Best Cupcake Recipe", text: "...")

let articleB = Article(
date: Date(),
title: "Best Cupcake Recipe",
text: "...",
Comment(user: currentUser, text: "Yep, can confirm!")
]
)
``````

## #78 Usages of throwing functions

🏈 A big benefit of using throwing functions for synchronous Swift APIs is that the caller can decide whether they want to treat the return value as optional (`try?`) or required (`try`).

``````func loadFile(named name: String) throws -> File {
guard let url = urlForFile(named: name) else {
throw File.Error.missing
}

do {
let data = try Data(contentsOf: url)
return File(url: url, data: data)
} catch {
throw File.Error.invalidData(error)
}
}

let requiredFile = try loadFile(named: "AppConfig.json")

let optionalFile = try? loadFile(named: "UserSettings.json")
``````

## #77 Nested generic types

🐝 Types that are nested in generics automatically inherit their parent's generic types - which is super useful when defining accessory types (for things like states or outcomes).

``````struct Task<Input, Output> {
typealias Closure = (Input) throws -> Output

let closure: Closure
}

enum Result {
case success(Output)
case failure(Error)
}
}
``````

## #76 Equatable & Hashable structures

🤖 Now that the Swift compiler automatically synthesizes Equatable & Hashable conformances for value types, it's easier than ever to setup model structures with nested types that are all `Equatable`/`Hashable`!

``````typealias Value = Hashable & Codable

struct User: Value {
var name: String
var age: Int
var settings: Settings
}

extension User {
struct Settings: Value {
var itemsPerPage: Int
var theme: Theme
}
}

extension User.Settings {
enum Theme: String, Value {
case light
case dark
}
}
``````

## #75 Conditional conformances

🎉 Swift 4.1 is here! One of the key features it brings is conditional conformances, which lets you have a type only conform to a protocol under certain constraints.

``````protocol UnboxTransformable {
associatedtype RawValue

static func transform(_ value: RawValue) throws -> Self?
}

extension Array: UnboxTransformable where Element: UnboxTransformable {
typealias RawValue = [Element.RawValue]

static func transform(_ value: RawValue) throws -> [Element]? {
return try value.compactMap(Element.transform)
}
}
``````

I also have an article with lots of more info on conditional conformances here. Paul Hudson also has a great overview of all Swift 4.1 features here.

## #74 Generic type aliases

🕵️‍♀️ A cool thing about Swift type aliases is that they can be generic! Combine that with tuples and you can easily define simple generic types.

``````typealias Pair<T> = (T, T)

extension Game {
func calculateScore(for players: Pair<Player>) -> Int {
...
}
}
``````

## #73 Parsing command line arguments using UserDefaults

☑️ A really cool "hidden" feature of UserDefaults is that it contains any arguments that were passed to the app at launch!

Super useful both in Swift command line tools & scripts, but also to temporarily override a value when debugging iOS apps.

``````let defaults = UserDefaults.standard
let query = defaults.string(forKey: "query")
let resultCount = defaults.integer(forKey: "results")
``````

## #72 Using the & operator

👏 Swift's `&` operator is awesome! Not only can you use it to compose protocols, you can compose other types too! Very useful if you want to hide concrete types & implementation details.

``````protocol LoadableFromURL {
}

...
}
}

class ViewControllerFactory {
func makeContentViewController() -> UIViewController & LoadableFromURL {
return ContentViewController()
}
}
``````

## #71 Capturing multiple values in mocks

🤗 When capturing values in mocks, using an array (instead of just a single value) makes it easy to verify that only a certain number of values were passed.

Perfect for protecting against "over-calling" something.

``````class UserManagerTests: XCTestCase {
func testObserversCalledWhenUserFirstLogsIn() {
let manager = UserManager()

let observer = ObserverMock()

// First login, observers should be notified
let user = User(id: 123, name: "John")
XCTAssertEqual(observer.users, [user])

// If the same user logs in again, observers shouldn't be notified
XCTAssertEqual(observer.users, [user])
}
}

private extension UserManagerTests {
class ObserverMock: UserManagerObserver {
private(set) var users = [User]()

func userDidChange(to user: User) {
users.append(user)
}
}
}
``````

## #70 Reducing the need for mocks

👋 When writing tests, you don't always need to create mocks - you can create stubs using real instances of things like errors, URLs & UserDefaults.

Here's how to do that for some common tasks/object types in Swift:

``````// Create errors using NSError (#function can be used to reference the name of the test)
let error = NSError(domain: #function, code: 1, userInfo: nil)

// Create non-optional URLs using file paths
let url = URL(fileURLWithPath: "Some/URL")

// Reference the test bundle using Bundle(for:)
let bundle = Bundle(for: type(of: self))

// Create an explicit UserDefaults object (instead of having to use a mock)
let userDefaults = UserDefaults(suiteName: #function)

// Create queues to control/await concurrent operations
let queue = DispatchQueue(label: #function)
``````

For when you actually do need mocking, check out "Mocking in Swift".

## #69 Using "then" as an external parameter label for closures

⏱ I've started using "then" as an external parameter label for completion handlers. Makes the call site read really nicely (Because I do ❤️ conversational API design) regardless of whether trailing closure syntax is used or not.

``````protocol DataLoader {
// Adding type aliases to protocols can be a great way to
// reduce verbosity for parameter types.
typealias Handler = (Result<Data>) -> Void
associatedtype Endpoint

func loadData(from endpoint: Endpoint, then handler: @escaping Handler)
}

...
}

...
})
``````

## #68 Combining lazily evaluated sequences with the builder pattern

😴 Combining lazily evaluated sequences with builder pattern-like properties can lead to some pretty sweet APIs for configurable sequences in Swift.

Also useful for queries & other things you "build up" and then execute.

``````// Extension adding builder pattern-like properties that return
// a new sequence value with the given configuration applied
extension FileSequence {
var recursive: FileSequence {
var sequence = self
sequence.isRecursive = true
return sequence
}

var includingHidden: FileSequence {
var sequence = self
sequence.includeHidden = true
return sequence
}
}

// BEFORE

let files = folder.makeFileSequence(recursive: true, includeHidden: true)

// AFTER

let files = folder.files.recursive.includingHidden
``````

Want an intro to lazy sequences? Check out "Swift sequences: The art of being lazy".

## #67 Faster & more stable UI tests

My top 3 tips for faster & more stable UI tests:

📱 Reset the app's state at the beginning of every test.

🆔 Use accessibility identifiers instead of UI strings.

⏱ Use expectations instead of waiting time.

``````func testOpeningArticle() {
// Launch the app with an argument that tells it to reset its state
let app = XCUIApplication()
app.launchArguments.append("--uitesting")
app.launch()

// Check that the app is displaying an activity indicator
let activityIndicator = app.activityIndicator.element
XCTAssertTrue(activityIndicator.exists)

expectation(for: NSPredicate(format: "exists == 0"),
evaluatedWith: activityIndicator)

// Use a generous timeout in case the network is slow
waitForExpectations(timeout: 10)

// Tap the cell for the first article
app.tables.cells["Article.0"].tap()

// Assert that a label with the accessibility identifier "Article.Title" exists
let label = app.staticTexts["Article.Title"]
XCTAssertTrue(label.exists)
}
``````

## #66 Accessing the clipboard from a Swift script

📋 It's super easy to access the contents of the clipboard from a Swift script. A big benefit of Swift scripting is being able to use Cocoa's powerful APIs for Mac apps.

``````import Cocoa

let clipboard = NSPasteboard.general.string(forType: .string)
``````

## #65 Using tuples for view state

🎯 Using Swift tuples for view state can be a super nice way to group multiple properties together and render them reactively using the layout system.

By using a tuple we don't have to either introduce a new type or make our view model-aware.

``````class TextView: UIView {
var state: (title: String?, text: String?) {
// By telling UIKit that our view needs layout and binding our
// state in layoutSubviews, we can react to state changes without
// doing unnecessary layout work.
didSet { setNeedsLayout() }
}

private let titleLabel = UILabel()
private let textLabel = UILabel()

override func layoutSubviews() {
super.layoutSubviews()

titleLabel.text = state.title
textLabel.text = state.text

...
}
}
``````

## #64 Throwing tests and LocalizedError

⚾️ Swift tests can throw, which is super useful in order to avoid complicated logic or force unwrapping. By making errors conform to `LocalizedError`, you can also get a nice error message in Xcode if there's a failure.

``````class ImageCacheTests: XCTestCase {
let bundle = Bundle(for: type(of: self))
let cache = ImageCache(bundle: bundle)

// bundle using this UIImage initializer
let image = try require(UIImage(named: "sample", in: bundle, compatibleWith: nil))
try cache.cache(image, forKey: "key")

let cachedImage = try cache.image(forKey: "key")
XCTAssertEqual(image, cachedImage)
}
}

enum ImageCacheError {
case emptyKey
case dataConversionFailed
}

// When using throwing tests, making your errors conform to
// LocalizedError will render a much nicer error message in
// Xcode (per default only the error code is shown).
extension ImageCacheError: LocalizedError {
var errorDescription: String? {
switch self {
case .emptyKey:
return "An empty key was given"
case .dataConversionFailed:
return "Failed to convert the given image to Data"
}
}
}
``````

For more information, and the implementation of the `require` method used above, check out "Avoiding force unwrapping in Swift unit tests".

## #63 The difference between static and class properties

✍️ Unlike `static` properties, `class` properties can be overridden by subclasses (however, they can't be stored, only computed).

``````class TableViewCell: UITableViewCell {
class var preferredHeight: CGFloat { return 60 }
}

class TallTableViewCell: TableViewCell {
override class var preferredHeight: CGFloat { return 100 }
}
``````

## #62 Creating extensions with static factory methods

👨‍🎨 Creating extensions with static factory methods can be a great alternative to subclassing in Swift, especially for things like setting up UIViews, CALayers or other kinds of styling.

It also lets you remove a lot of styling & setup from your view controllers.

``````extension UILabel {
static func makeForTitle() -> UILabel {
let label = UILabel()
label.font = .boldSystemFont(ofSize: 24)
label.textColor = .darkGray
label.minimumScaleFactor = 0.75
return label
}

static func makeForText() -> UILabel {
let label = UILabel()
label.font = .systemFont(ofSize: 16)
label.textColor = .black
label.numberOfLines = 0
return label
}
}

class ArticleViewController: UIViewController {
lazy var titleLabel = UILabel.makeForTitle()
lazy var textLabel = UILabel.makeForText()
}
``````

## #61 Child view controller auto-resizing

🧒 An awesome thing about child view controllers is that they're automatically resized to match their parent, making them a super nice solution for things like loading & error views.

``````class ListViewController: UIViewController {

self?.handle(result)
}
}
}
``````

For more about child view controller (including the `add` and `remove` methods used above), check out "Using child view controllers as plugins in Swift".

## #60 Using zip

🤐 Using the zip function in Swift you can easily combine two sequences. Super useful when using two sequences to do some work, since zip takes care of all the bounds-checking.

``````func render(titles: [String]) {
for (label, text) in zip(titleLabels, titles) {
print(text)
label.text = text
}
}
``````

## #59 Defining custom option sets

🎛 The awesome thing about option sets in Swift is that they can automatically either be passed as a single member or as a set. Even cooler is that you can easily define your own option sets as well, perfect for options and other non-exclusive values.

``````// Option sets are awesome, because you can easily pass them
// both using dot syntax and array literal syntax, like when
// using the UIView animation API:
UIView.animate(withDuration: 0.3,
delay: 0,
options: .allowUserInteraction,
animations: animations)

UIView.animate(withDuration: 0.3,
delay: 0,
options: [.allowUserInteraction, .layoutSubviews],
animations: animations)

// The cool thing is that you can easily define your own option
// sets as well, by defining a struct that has an Int rawValue,
// that will be used as a bit mask.
extension Cache {
struct Options: OptionSet {
static let saveToDisk = Options(rawValue: 1)
static let clearOnMemoryWarning = Options(rawValue: 1 << 1)
static let clearDaily = Options(rawValue: 1 << 2)

let rawValue: Int
}
}

// We can now use Cache.Options just like UIViewAnimationOptions:
Cache(options: .saveToDisk)
Cache(options: [.saveToDisk, .clearDaily])
``````

## #58 Using the where clause with associated types

🙌 Using the `where` clause when designing protocol-oriented APIs in Swift can let your implementations (or others' if it's open source) have a lot more freedom, especially when it comes to collections.

``````public protocol PathFinderMap {
associatedtype Node
// Using the 'where' clause for associated types, we can
// ensure that a type meets certain requirements (in this
// case that it's a sequence with Node elements).
associatedtype NodeSequence: Sequence where NodeSequence.Element == Node

// Instead of using a concrete type (like [Node]) here, we
// give implementors of this protocol more freedom while
// still meeting our requirements. For example, one
// implementation might use Set<Node>.
func neighbors(of node: Node) -> NodeSequence
}
``````

## #57 Using first class functions when iterating over a dictionary

👨‍🍳 Combine first class functions in Swift with the fact that Dictionary elements are (Key, Value) tuples and you can build yourself some pretty awesome functional chains when iterating over a Dictionary.

``````func makeActor(at coordinate: Coordinate, for building: Building) -> Actor {
let actor = Actor()
actor.position = coordinate.point
actor.animation = building.animation
return actor
}

func render(_ buildings: [Coordinate : Building]) {
}
``````

## #56 Calling instance methods as static functions

😎 In Swift, you can call any instance method as a static function and it will return a closure representing that method. This is how running tests using SPM on Linux works.

``````// This produces a '() -> Void' closure which is a reference to the
// given view's 'removeFromSuperview' method.
let closure = UIView.removeFromSuperview(view)

// We can now call it just like we would any other closure, and it
// will run 'view.removeFromSuperview()'
closure()

// This is how running tests using the Swift Package Manager on Linux
// works, you return your test functions as closures:
extension UserManagerTests {
static var allTests = [
("testLoggingIn", testLoggingIn),
("testLoggingOut", testLoggingOut),
("testUserPermissions", testUserPermissions)
]
}
``````

## #55 Dropping suffixes from method names to support multiple arguments

👏 One really nice benefit of dropping suffixes from method names (and just using verbs, when possible) is that it becomes super easy to support both single and multiple arguments, and it works really well semantically.

``````extension UIView {
}
}

// By dropping the "Subview" suffix from the method name, both
// single and multiple arguments work really well semantically.
``````

## #54 Constraining protocols to classes to ensure mutability

👽 Using the `AnyObject` (or `class`) constraint on protocols is not only useful when defining delegates (or other weak references), but also when you always want instances to be mutable without copying.

``````// By constraining a protocol with 'AnyObject' it can only be adopted
// by classes, which means all instances will always be mutable, and
// that it's the original instance (not a copy) that will be mutated.
protocol DataContainer: AnyObject {
var data: Data? { get set }
}

class UserSettingsManager {
private var settings: Settings
private let dataContainer: DataContainer

// Since DataContainer is a protocol, we an easily mock it in
// tests if we use dependency injection
init(settings: Settings, dataContainer: DataContainer) {
self.settings = settings
self.dataContainer = dataContainer
}

func saveSettings() throws {
let data = try settings.serialize()

// We can now assign properties on an instance of our protocol
// because the compiler knows it's always going to be a class
dataContainer.data = data
}
}
``````

## #53 String-based enums in string interpolation

🍣 Even if you define a custom raw value for a string-based enum in Swift, the full case name will be used in string interpolation.

Super useful when using separate raw values for JSON, while still wanting to use the full case name in other contexts.

``````extension Building {
// This enum has custom raw values that are used when decoding
// a value, for example from JSON.
enum Kind: String {
case castle = "C"
case town = "T"
case barracks = "B"
case goldMine = "G"
case camp = "CA"
case blacksmith = "BL"
}

var animation: Animation {
return Animation(
// When used in string interpolation, the full case name is still used.
// For 'castle' this will be 'buildings/castle'.
name: "buildings/\(kind)",
frameCount: frameCount,
frameDuration: frameDuration
)
}
}
``````

## #52 Expressively comparing a value with a list of candidates

👨‍🔬 Continuing to experiment with expressive ways of comparing a value with a list of candidates in Swift. Adding an extension on Equatable is probably my favorite approach so far.

``````extension Equatable {
func isAny(of candidates: Self...) -> Bool {
return candidates.contains(self)
}
}

let isHorizontal = direction.isAny(of: .left, .right)
``````

See tip #35 for my previous experiment.

## #51 UIView bounds and transforms

📐 A really interesting side-effect of a `UIView`'s `bounds` being its rect within its own coordinate system is that transforms don't affect it at all. That's why it's usually a better fit than `frame` when doing layout calculations of subviews.

``````let view = UIView()
view.frame.size = CGSize(width: 100, height: 100)
view.transform = CGAffineTransform(scaleX: 2, y: 2)

print(view.frame) // (-50.0, -50.0, 200.0, 200.0)
print(view.bounds) // (0.0, 0.0, 100.0, 100.0)
``````

## #50 UIKit default arguments

👏 It's awesome that many UIKit APIs with completion handlers and other optional parameters import into Swift with default arguments (even though they are written in Objective-C). Getting rid of all those nil arguments is so nice!

``````// BEFORE: All parameters are specified, just like in Objective-C

viewController.present(modalViewController, animated: true, completion: nil)

modalViewController.dismiss(animated: true, completion: nil)

to: contentViewController,
duration: 0.3,
options: [],
animations: animations,
completion: nil)

// AFTER: Since many UIKit APIs with completion handlers and other
// optional parameters import into Swift with default arguments,
// we can make our calls shorter

viewController.present(modalViewController, animated: true)

modalViewController.dismiss(animated: true)

to: contentViewController,
duration: 0.3,
animations: animations)
``````

## #49 Avoiding Massive View Controllers

✂️ Avoiding Massive View Controllers is all about finding the right levels of abstraction and splitting things up.

My personal rule of thumb is that as soon as I have 3 methods or properties that have the same prefix, I break them out into their own type.

``````// BEFORE

private lazy var signUpLabel = UILabel()
private lazy var signUpImageView = UIImageView()
private lazy var signUpButton = UIButton()
}

// AFTER

private lazy var signUpView = SignUpView()
}

class SignUpView: UIView {
private lazy var label = UILabel()
private lazy var imageView = UIImageView()
private lazy var button = UIButton()
}
``````

## #48 Extending optionals

❤️ I love the fact that optionals are enums in Swift - it makes it so easy to extend them with convenience APIs for certain types. Especially useful when doing things like data validation on optional values.

``````func validateTextFields() -> Bool {
return false
}

...

return true
}

// Since all optionals are actual enum values in Swift, we can easily
// extend them for certain types, to add our own convenience APIs

extension Optional where Wrapped == String {
var isNilOrEmpty: Bool {
switch self {
case let string?:
return string.isEmpty
case nil:
return true
}
}
}

// Since strings are now Collections in Swift 4, you can even
// add this property to all optional collections:

extension Optional where Wrapped: Collection {
var isNilOrEmpty: Bool {
switch self {
case let collection?:
return collection.isEmpty
case nil:
return true
}
}
}
``````

## #47 Using where with for-loops

🗺 Using the `where` keyword can be a super nice way to quickly apply a filter in a `for`-loop in Swift. You can of course use `map`, `filter` and `forEach`, or `guard`, but for simple loops I think this is very expressive and nice.

``````func archiveMarkedPosts() {
for post in posts where post.isMarked {
archive(post)
}
}

func healAllies() {
for player in players where player.isAllied(to: currentPlayer) {
player.heal()
}
}
``````

👻 Variable shadowing can be super useful in Swift, especially when you want to create a local copy of a parameter value in order to use it as state within a closure.

``````init(repeatMode: RepeatMode, closure: @escaping () -> UpdateOutcome) {
// Shadow the argument with a local, mutable copy
var repeatMode = repeatMode

self.closure = {
// With shadowing, there's no risk of accidentially
// referring to the immutable version
switch repeatMode {
case .forever:
break
case .times(let count):
guard count > 0 else {
return .finished
}

// We can now capture the mutable version and use
// it for state in a closure
repeatMode = .times(count - 1)
}

return closure()
}
}
``````

## #45 Using dot syntax for static properties and initializers

✒️ Dot syntax is one of my favorite features of Swift. What's really cool is that it's not only for enums, any static method or property can be used with dot syntax - even initializers! Perfect for convenience APIs and default parameters.

``````public enum RepeatMode {
case times(Int)
case forever
}

public extension RepeatMode {
static var never: RepeatMode {
return .times(0)
}

static var once: RepeatMode {
return .times(1)
}
}

view.perform(animation, repeated: .once)

// To make default parameters more compact, you can even use init with dot syntax

init(cache: Cache = .init(), decoder: ImageDecoder = .init()) {
...
}
}
``````

## #44 Calling functions as closures with a tuple as parameters

🚀 One really cool aspect of Swift having first class functions is that you can pass any function (or even initializer) as a closure, and even call it with a tuple containing its parameters!

``````// This function lets us treat any "normal" function or method as
// a closure and run it with a tuple that contains its parameters
func call<Input, Output>(_ function: (Input) -> Output, with input: Input) -> Output {
return function(input)
}

class ViewFactory {
// We can now pass an initializer as a closure, and a tuple
// containing its parameters
}

private func loadTextStyles() -> (font: UIFont, color: UIColor) {
return (theme.font, theme.textColor)
}
}

init(font: UIFont, textColor: UIColor) {
...
}
}
``````

## #43 Enabling static dependency injection

💉 If you've been struggling to test code that uses static APIs, here's a technique you can use to enable static dependency injection without having to modify any call sites:

``````// Before: Almost impossible to test due to the use of singletons

class Analytics {
static func log(_ event: Event) {
Database.shared.save(event)

let dictionary = event.serialize()
NetworkManager.shared.post(dictionary, to: eventURL)
}
}

// After: Much easier to test, since we can inject mocks as arguments

class Analytics {
static func log(_ event: Event,
database: Database = .shared,
networkManager: NetworkManager = .shared) {
database.save(event)

let dictionary = event.serialize()
networkManager.post(dictionary, to: eventURL)
}
}
``````

## #42 Type inference for lazy properties in Swift 4

🎉 In Swift 4, type inference works for lazy properties and you don't need to explicitly refer to `self`!

``````// Swift 3

class PurchaseView: UIView {

private func makeBuyButton() -> UIButton {
let button = UIButton()
button.setTitleColor(.blue, for: .normal)
return button
}
}

// Swift 4

class PurchaseView: UIView {

private func makeBuyButton() -> UIButton {
let button = UIButton()
button.setTitleColor(.blue, for: .normal)
return button
}
}
``````

## #41 Converting Swift errors to NSError

😎 You can turn any Swift `Error` into an `NSError`, which is super useful when pattern matching with a code 👍. Also, switching on optionals is pretty cool!

``````let task = urlSession.dataTask(with: url) { data, _, error in
switch error {
case .some(let error as NSError) where error.code == NSURLErrorNotConnectedToInternet:
presenter.showOfflineView()
case .some(let error):
presenter.showGenericErrorView()
case .none:
presenter.renderContent(from: data)
}
}

``````

Also make sure to check out Kostas Kremizas' tip about how you can pattern match directly against a member of `URLError`.

## #40 Making UIImage macOS compatible

🖥 Here's an easy way to make iOS model code that uses `UIImage` macOS compatible - like me and Gui Rambo discussed on the Swift by Sundell Podcast.

``````// Either put this in a separate file that you only include in your macOS target or wrap the code in #if os(macOS) / #endif

import Cocoa

// Step 1: Typealias UIImage to NSImage
typealias UIImage = NSImage

// Step 2: You might want to add these APIs that UIImage has but NSImage doesn't.
extension NSImage {
var cgImage: CGImage? {
var proposedRect = CGRect(origin: .zero, size: size)

return cgImage(forProposedRect: &proposedRect,
context: nil,
hints: nil)
}

convenience init?(named name: String) {
self.init(named: Name(name))
}
}

// Step 3: Profit - you can now make your model code that uses UIImage cross-platform!
struct User {
let name: String
let profileImage: UIImage
}
``````

## #39 Internally mutable protocol-oriented APIs

🤖 You can easily define a protocol-oriented API that can only be mutated internally, by using an internal protocol that extends a public one.

``````// Declare a public protocol that acts as your immutable API
public protocol ModelHolder {
associatedtype Model
var model: Model { get }
}

// Declare an extended, internal protocol that provides a mutable API
internal protocol MutableModelHolder: ModelHolder {
var model: Model { get set }
}

// You can now implement the requirements using 'public internal(set)'
public class UserHolder: MutableModelHolder {
public internal(set) var model: User

internal init(model: User) {
self.model = model
}
}
``````

## #38 Switching on a set

🎛 You can switch on a set using array literals as cases in Swift! Can be really useful to avoid many `if`/`else if` statements.

``````class RoadTile: Tile {
var connectedDirections = Set<Direction>()

func render() {
switch connectedDirections {
case [.up, .down]:
case [.left, .right]:
default:
}
}
}
``````

## #37 Adding the current locale to cache keys

🌍 When caching localized content in an app, it's a good idea to add the current locale to all keys, to prevent bugs when switching languages.

``````func cache(_ content: Content, forKey key: String) throws {
let data = try wrap(content) as Data
let key = localize(key: key)
try storage.store(data, forKey: key)
}

func loadCachedContent(forKey key: String) -> Content? {
let key = localize(key: key)
return data.flatMap { try? unbox(data: \$0) }
}

private func localize(key: String) -> String {
return key + "-" + Bundle.main.preferredLocalizations[0]
}
``````

## #36 Setting up tests to avoid retain cycles with weak references

🚳 Here's an easy way to setup a test to avoid accidental retain cycles with object relationships (like weak delegates & observers) in Swift:

``````func testDelegateNotRetained() {
// Assign the delegate (weak) and also retain it using a local var
var delegate: Delegate? = DelegateMock()
controller.delegate = delegate
XCTAssertNotNil(controller.delegate)

// Release the local var, which should also release the weak reference
delegate = nil
XCTAssertNil(controller.delegate)
}
``````

## #35 Expressively matching a value against a list of candidates

👨‍🔬 Playing around with an expressive way to check if a value matches any of a list of candidates in Swift:

``````// Instead of multiple conditions like this:

if string == "One" || string == "Two" || string == "Three" {

}

// You can now do:

if string == any(of: "One", "Two", "Three") {

}
``````

You can find a gist with the implementation here.

## #34 Organizing code using extensions

👪 APIs in a Swift extension automatically inherit its access control level, making it a neat way to organize public, internal & private APIs.

``````public extension Animation {
init(textureNamed textureName: String) {
frames = [Texture(name: textureName)]
}

init(texturesNamed textureNames: [String], frameDuration: TimeInterval = 1) {
frames = textureNames.map(Texture.init)
self.frameDuration = frameDuration
}

init(image: Image) {
frames = [Texture(image: image)]
}
}

internal extension Animation {
}
}
``````

## #33 Using map to transform an optional into a Result type

🗺 Using `map` you can transform an optional value into an optional `Result` type by simply passing in the enum case.

``````enum Result<Value> {
case value(Value)
case error(Error)
}

class Promise<Value> {
private var result: Result<Value>?

init(value: Value? = nil) {
result = value.map(Result.value)
}
}
``````

## #32 Assigning to self in struct initializers

👌 It's so nice that you can assign directly to `self` in `struct` initializers in Swift. Very useful when adding conformance to protocols.

``````extension Bool: AnswerConvertible {
public init(input: String) throws {
switch input.lowercased() {
case "y", "yes", "👍":
self = true
default:
self = false
}
}
}
``````

## #31 Recursively calling closures as inline functions

☎️ Defining Swift closures as inline functions enables you to recursively call them, which is super useful in things like custom sequences.

``````class Database {
func records(matching query: Query) -> AnySequence<Record> {

func iterate() -> Record? {
guard let nextRecord = recordIterator.next() else {
return nil
}

guard nextRecord.matches(query) else {
// Since the closure is an inline function, it can be recursively called,
// in this case in order to advance to the next item.
return iterate()
}

return nextRecord
}

// AnySequence/AnyIterator are part of the standard library and provide an easy way
// to define custom sequences using closures.
return AnySequence { AnyIterator(iterate) }
}
}
``````

Rob Napier points out that using the above might cause crashes if used on a large databaset, since Swift has no guaranteed Tail Call Optimization (TCO).

Slava Pestov also points out that another benefit of inline functions vs closures is that they can have their own generic parameter list.

## #30 Passing self to required Objective-C dependencies

🏖 Using lazy properties in Swift, you can pass `self` to required Objective-C dependencies without having to use force-unwrapped optionals.

``````class DataLoader: NSObject {
lazy var urlSession: URLSession = self.makeURLSession()

private func makeURLSession() -> URLSession {
return URLSession(configuration: .default, delegate: self, delegateQueue: .main)
}
}

class Renderer {

}
}
``````

## #29 Making weak or lazy properties readonly

👓 If you have a property in Swift that needs to be `weak` or `lazy`, you can still make it readonly by using `private(set)`.

``````class Node {
private(set) weak var parent: Node?
private(set) lazy var children = [Node]()

children.append(child)
child.parent = self
}
}
``````

## #28 Defining static URLs using string literals

🌏 Tired of using `URL(string: "url")!` for static URLs? Make `URL` conform to `ExpressibleByStringLiteral` and you can now simply use `"url"` instead.

``````extension URL: ExpressibleByStringLiteral {
// By using 'StaticString' we disable string interpolation, for safety
public init(stringLiteral value: StaticString) {
self = URL(string: "\(value)").require(hint: "Invalid URL string literal: \(value)")
}
}

// We can now define URLs using static string literals 🎉
let url: URL = "https://www.swiftbysundell.com"

// In Swift 3 or earlier, you also have to implement 2 additional initializers
extension URL {
public init(extendedGraphemeClusterLiteral value: StaticString) {
self.init(stringLiteral: value)
}

public init(unicodeScalarLiteral value: StaticString) {
self.init(stringLiteral: value)
}
}
``````

To find the extension that adds the `require()` method on `Optional` that I use above, check out Require.

## #27 Manipulating points, sizes and frames using math operators

✚ I'm always careful with operator overloading, but for manipulating things like sizes, points & frames I find them super useful.

``````extension CGSize {
static func *(lhs: CGSize, rhs: CGFloat) -> CGSize {
return CGSize(width: lhs.width * rhs, height: lhs.height * rhs)
}
}

button.frame.size = image.size * 2
``````

If you like the above idea, check out CGOperators, which contains math operator overloads for all Core Graphics' vector types.

## #26 Using closure types in generic constraints

🔗 You can use closure types in generic constraints in Swift. Enables nice APIs for handling sequences of closures.

``````extension Sequence where Element == () -> Void {
func callAll() {
forEach { \$0() }
}
}

extension Sequence where Element == () -> String {
func joinedResults(separator: String) -> String {
return map { \$0() }.joined(separator: separator)
}
}

callbacks.callAll()
let names = nameProviders.joinedResults(separator: ", ")
``````

(If you're using Swift 3, you have to change `Element` to `Iterator.Element`)

## #25 Using associated enum values to avoid state-specific optionals

🎉 Using associated enum values is a super nice way to encapsulate mutually exclusive state info (and avoiding state-specific optionals).

``````// BEFORE: Lots of state-specific, optional properties

class Player {
var isWaitingForMatchMaking: Bool
var invitingUser: User?
var numberOfLives: Int
var playerDefeatedBy: Player?
var roundDefeatedIn: Int?
}

// AFTER: All state-specific information is encapsulated in enum cases

class Player {
enum State {
case waitingForMatchMaking
case waitingForInviteResponse(from: User)
case active(numberOfLives: Int)
case defeated(by: Player, roundNumber: Int)
}

var state: State
}
``````

## #24 Using enums for async result types

👍 I really like using enums for all async result types, even boolean ones. Self-documenting, and makes the call site a lot nicer to read too!

``````protocol PushNotificationService {
// Before
func enablePushNotifications(completionHandler: @escaping (Bool) -> Void)

// After
}

case enabled
case disabled
}

if status == .enabled {
}
}
``````

## #23 Working on async code in a playground

🏃 Want to work on your async code in a Swift Playground? Just set `needsIndefiniteExecution` to true to keep it running:

``````import PlaygroundSupport

PlaygroundPage.current.needsIndefiniteExecution = true

let greeting = "Hello after 3 seconds"
print(greeting)
}
``````

To stop the playground from executing, simply call `PlaygroundPage.current.finishExecution()`.

## #22 Overriding self with a weak reference

💦 Avoid memory leaks when accidentially refering to `self` in closures by overriding it locally with a weak reference:

Swift >= 4.2

``````dataLoader.loadData(from: url) { [weak self] result in
guard let self = self else {
return
}

self.cache(result)

...
``````

Swift < 4.2

``````dataLoader.loadData(from: url) { [weak self] result in
guard let `self` = self else {
return
}

self.cache(result)

...
``````

Note that the reason the above currently works is because of a compiler bug (which I hope gets turned into a properly supported feature soon).

## #21 Using DispatchWorkItem

🕓 Using dispatch work items you can easily cancel a delayed asynchronous GCD task if you no longer need it:

``````let workItem = DispatchWorkItem {
// Your async code goes in here
}

// Execute the work item after 1 second
DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: workItem)

// You can cancel the work item if you no longer need it
workItem.cancel()
``````

## #20 Combining a sequence of functions

➕ While working on a new Swift developer tool (to be open sourced soon 😉), I came up with a pretty neat way of organizing its sequence of operations, by combining their functions into a closure:

``````internal func +<A, B, C>(lhs: @escaping (A) throws -> B,
rhs: @escaping (B) throws -> C) -> (A) throws -> C {
return { try rhs(lhs(\$0)) }
}

public func run() throws {
try (determineTarget + build + analyze + output)()
}
``````

If you're familiar with the functional programming world, you might know the above technique as the pipe operator (thanks to Alexey Demedreckiy for pointing this out!)

## #19 Chaining optionals with map() and flatMap()

🗺 Using `map()` and `flatMap()` on optionals you can chain multiple operations without having to use lengthy `if lets` or `guards`:

``````// BEFORE

guard let string = argument(at: 1) else {
return
}

guard let url = URL(string: string) else {
return
}

handle(url)

// AFTER

argument(at: 1).flatMap(URL.init).map(handle)
``````

## #18 Using self-executing closures for lazy properties

🚀 Using self-executing closures is a great way to encapsulate lazy property initialization:

``````class StoreViewController: UIViewController {
private lazy var collectionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
let view = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout)
view.delegate = self
view.dataSource = self
return view
}()

}
}
``````

## #17 Speeding up Swift package tests

⚡️ You can speed up your Swift package tests using the `--parallel` flag. For Marathon, the tests execute 3 times faster that way!

``````swift test --parallel
``````

## #16 Avoiding mocking UserDefaults

🛠 Struggling with mocking `UserDefaults` in a test? The good news is: you don't need mocking - just create a real instance:

``````class LoginTests: XCTestCase {
private var userDefaults: UserDefaults!

override func setUp() {
super.setup()

userDefaults = UserDefaults(suiteName: #file)
userDefaults.removePersistentDomain(forName: #file)

}
}
``````

👍 Using variadic parameters in Swift, you can create some really nice APIs that take a list of objects without having to use an array:

``````extension Canvas {
}
}

let circle = Circle(center: CGPoint(x: 5, y: 5), radius: 5)
let lineA = Line(start: .zero, end: CGPoint(x: 10, y: 10))
let lineB = Line(start: CGPoint(x: 0, y: 10), end: CGPoint(x: 10, y: 0))

let canvas = Canvas()
canvas.render()
``````

## #14 Referring to enum cases with associated values as closures

😮 Just like you can refer to a Swift function as a closure, you can do the same thing with enum cases with associated values:

``````enum UnboxPath {
case key(String)
case keyPath(String)
}

struct UserSchema {
static let name = key("name")
static let age = key("age")
static let posts = key("posts")

private static let key = UnboxPath.key
}
``````

## #13 Using the === operator to compare objects by instance

📈 The `===` operator lets you check if two objects are the same instance. Very useful when verifying that an array contains an instance in a test:

``````protocol InstanceEquatable: class, Equatable {}

extension InstanceEquatable {
static func ==(lhs: Self, rhs: Self) -> Bool {
return lhs === rhs
}
}

extension Enemy: InstanceEquatable {}

func testDestroyingEnemy() {
player.attack(enemy)
XCTAssertTrue(player.destroyedEnemies.contains(enemy))
}
``````

## #12 Calling initializers with dot syntax and passing them as closures

😎 Cool thing about Swift initializers: you can call them using dot syntax and pass them as closures! Perfect for mocking dates in tests.

``````class Logger {
private let storage: LogStorage
private let dateProvider: () -> Date

init(storage: LogStorage = .init(), dateProvider: @escaping () -> Date = Date.init) {
self.storage = storage
self.dateProvider = dateProvider
}

func log(event: Event) {
storage.store(event: event, date: dateProvider())
}
}
``````

## #11 Structuring UI tests as extensions on XCUIApplication

📱 Most of my UI testing logic is now categories on `XCUIApplication`. Makes the test cases really easy to read:

``````func testLoggingInAndOut() {
XCTAssertFalse(app.userIsLoggedIn)

app.launch()
XCTAssertTrue(app.userIsLoggedIn)

app.logout()
XCTAssertFalse(app.userIsLoggedIn)
}

func testDisplayingCategories() {
XCTAssertFalse(app.isDisplayingCategories)

app.launch()
app.goToCategories()
XCTAssertTrue(app.isDisplayingCategories)
}
``````

## #10 Avoiding default cases in switch statements

🙂 It’s a good idea to avoid “default” cases when switching on Swift enums - it’ll “force you” to update your logic when a new case is added:

``````enum State {
case loggedIn
case loggedOut
case onboarding
}

func handle(_ state: State) {
switch state {
case .loggedIn:
showMainUI()
case .loggedOut:
// Compiler error: Switch must be exhaustive
}
}
``````

## #9 Using the guard statement in many different scopes

💂 It's really cool that you can use Swift's 'guard' statement to exit out of pretty much any scope, not only return from functions:

``````// You can use the 'guard' statement to...

for string in strings {
// ...continue an iteration
guard shouldProcess(string) else {
continue
}

// ...or break it
guard !shouldBreak(for: string) else {
break
}

// ...or return
guard !shouldReturn(for: string) else {
return
}

// ..or throw an error
guard string.isValid else {
throw StringError.invalid(string)
}

// ...or exit the program
guard !shouldExit(for: string) else {
exit(1)
}
}
``````

## #8 Passing functions & operators as closures

❤️ Love how you can pass functions & operators as closures in Swift. For example, it makes the syntax for sorting arrays really nice!

``````let array = [3, 9, 1, 4, 6, 2]
let sorted = array.sorted(by: <)
``````

## #7 Using #function for UserDefaults key consistency

🗝 Here's a neat little trick I use to get UserDefault key consistency in Swift (#function expands to the property name in getters/setters). Just remember to write a good suite of tests that'll guard you against bugs when changing property names.

``````extension UserDefaults {
var onboardingCompleted: Bool {
get { return bool(forKey: #function) }
set { set(newValue, forKey: #function) }
}
}
``````

## #6 Using a name already taken by the standard library

📛 Want to use a name already taken by the standard library for a nested type? No problem - just use `Swift.` to disambiguate:

``````extension Command {
enum Error: Swift.Error {
case missing
case invalid(String)
}
}
``````

## #5 Using Wrap to implement Equatable

📦 Playing around with using Wrap to implement `Equatable` for any type, primarily for testing:

``````protocol AutoEquatable: Equatable {}

extension AutoEquatable {
static func ==(lhs: Self, rhs: Self) -> Bool {
let lhsData = try! wrap(lhs) as Data
let rhsData = try! wrap(rhs) as Data
return lhsData == rhsData
}
}
``````

## #4 Using typealiases to reduce the length of method signatures

📏 One thing that I find really useful in Swift is to use typealiases to reduce the length of method signatures in generic types:

``````public class PathFinder<Object: PathFinderObject> {
public typealias Map = Object.Map
public typealias Node = Map.Node
public typealias Path = PathFinderPath<Object>

public static func possiblePaths(for object: Object, at rootNode: Node, on map: Map) -> Path.Sequence {
return .init(object: object, rootNode: rootNode, map: map)
}
}
``````

## #3 Referencing either external or internal parameter name when writing docs

📖 You can reference either the external or internal parameter label when writing Swift docs - and they get parsed the same:

``````// EITHER:

class Foo {
/**
*   - parameter string: A string
*/
func bar(with string: String) {}
}

// OR:

class Foo {
/**
*   - parameter with: A string
*/
func bar(with string: String) {}
}
``````

## #2 Using auto closures

👍 Finding more and more uses for auto closures in Swift. Can enable some pretty nice APIs:

``````extension Dictionary {
mutating func value(for key: Key, orAdd valueClosure: @autoclosure () -> Value) -> Value {
if let value = self[key] {
return value
}

let value = valueClosure()
self[key] = value
return value
}
}
``````

## #1 Namespacing with nested types

🚀 I’ve started to become a really big fan of nested types in Swift. Love the additional namespacing it gives you!

``````public struct Map {
public struct Model {
public let size: Size
public let theme: Theme
public var terrain: [Position : Terrain.Model]
public var units: [Position : Unit.Model]
public var buildings: [Position : Building.Model]
}

public enum Direction {
case up
case right
case down
case left
}

public struct Position {
public var x: Int
public var y: Int
}

public enum Size: String {
case small = "S"
case medium = "M"
case large = "L"
case extraLarge = "XL"
}
}``````

Author: JohnSundell
Source code: https://github.com/JohnSundell/SwiftTips

#swift

1605017502

## The Difference Between Regular Functions and Arrow Functions in JavaScript

Other then the syntactical differences. The main difference is the way the this keyword behaves? In an arrow function, the this keyword remains the same throughout the life-cycle of the function and is always bound to the value of this in the closest non-arrow parent function. Arrow functions can never be constructor functions so they can never be invoked with the new keyword. And they can never have duplicate named parameters like a regular function not using strict mode.

###### Here are a few code examples to show you some of the differences
```this.name = "Bob";
const person = {
name: “Jon”,
```<span style="color: #008000">// Regular function</span>
func1: <span style="color: #0000ff">function</span> () {
console.log(<span style="color: #0000ff">this</span>);
},

<span style="color: #008000">// Arrow function</span>
func2: () =&gt; {
console.log(<span style="color: #0000ff">this</span>);
}
```
}
person.func1(); // Call the Regular function
// Output: {name:“Jon”, func1:[Function: func1], func2:[Function: func2]}
person.func2(); // Call the Arrow function
// Output: {name:“Bob”}```

###### The new keyword with an arrow function
```const person = (name) => console.log("Your name is " + name);
const bob = new person("Bob");
// Uncaught TypeError: person is not a constructor```

###### If you want to see a visual presentation on the differences, then you can see the video below:

#arrow functions #javascript #regular functions #arrow functions vs normal functions #difference between functions and arrow functions

1661577180

## SwiftTips

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 account!

## Property Wrappers as Debugging Tools

Property Wrappers allow developers to wrap properties with specific behaviors, that will be seamlessly triggered whenever the properties are accessed.

While their primary use case is to implement business logic within our apps, it's also possible to use Property Wrappers as debugging tools!

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.

``````import Foundation

@propertyWrapper
struct History<Value> {
private var value: Value
private(set) var history: [Value] = []

init(wrappedValue: Value) {
self.value = wrappedValue
}

var wrappedValue: Value {
get { value }

set {
history.append(value)
value = newValue
}
}

var projectedValue: Self {
return self
}
}

// We can then decorate our business code
// with the `@History` wrapper
struct User {
@History var name: String = ""
}

var user = User()

// All the existing call sites will still
// compile, without the need for any change
user.name = "John"
user.name = "Jane"

// But now we can also access an history of
// all the previous values!
user.\$name.history // ["", "John"]
``````

## Localization through `String` interpolation

Swift 5 gave us the possibility to define our own custom `String` interpolation methods.

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.

``````import Foundation

extension String.StringInterpolation {
mutating func appendInterpolation(localized key: String, _ args: CVarArg...) {
let localized = String(format: NSLocalizedString(key, comment: ""), arguments: args)
appendLiteral(localized)
}
}

/*
Let's assume that this is the content of our Localizable.strings:

"welcome.screen.greetings" = "Hello %@!";
*/

print("\(localized: "welcome.screen.greetings", userName)") // Hello John!
``````

## Implementing pseudo-inheritance between `structs`

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!

Using the new KeyPath-based dynamic member lookup, you can implement some pseudo-inheritance, where a type inherits the API of another one 🎉

(However, be careful, I’m definitely not advocating inheritance as a go-to solution 🙃)

``````import Foundation

protocol Inherits {
associatedtype SuperType

var `super`: SuperType { get }
}

extension Inherits {
subscript<T>(dynamicMember keyPath: KeyPath<SuperType, T>) -> T {
return self.`super`[keyPath: keyPath]
}
}

struct Person {
let name: String
}

@dynamicMemberLookup
struct User: Inherits {
let `super`: Person

}

user.name // "John Appleseed"
``````

## Composing `NSAttributedString` through a Function Builder

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.

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.

``````import UIKit

@_functionBuilder
class NSAttributedStringBuilder {
static func buildBlock(_ components: NSAttributedString...) -> NSAttributedString {
let result = NSMutableAttributedString(string: "")

return components.reduce(into: result) { (result, current) in result.append(current) }
}
}

extension NSAttributedString {
class func composing(@NSAttributedStringBuilder _ parts: () -> NSAttributedString) -> NSAttributedString {
return parts()
}
}

let result = NSAttributedString.composing {
NSAttributedString(string: "Hello",
attributes: [.font: UIFont.systemFont(ofSize: 24),
.foregroundColor: UIColor.red])
NSAttributedString(string: " world!",
attributes: [.font: UIFont.systemFont(ofSize: 20),
.foregroundColor: UIColor.orange])
}
``````

## Using `switch` and `if` as expressions

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:

``````let constant = if condition {
someValue
} else {
someOtherValue
}
``````

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.

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.

``````import Foundation

func resultOf<T>(_ code: () -> T) -> T {
return code()
}

let randomInt = Int.random(in: 0...3)

let spelledOut: String = resultOf {
switch randomInt {
case 0:
return "Zero"
case 1:
return "One"
case 2:
return "Two"
case 3:
return "Three"
default:
return "Out of range"
}
}

print(spelledOut)
``````

## Avoiding double negatives within `guard` statements

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.

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.

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.

``````import Foundation

extension Collection {
var hasElements: Bool {
return !isEmpty
}
}

let array = Bool.random() ? [1, 2, 3] : []

guard array.hasElements else { fatalError("array was empty") }

print(array)
``````

## Defining a custom `init` without loosing the compiler-generated one

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`.

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.

``````import Foundation

struct Point {
let x: Int
let y: Int
}

extension Point {
init() {
x = 0
y = 0
}
}

let usingDefaultInit = Point(x: 4, y: 3)
let usingCustomInit = Point()
``````

## Implementing a namespace through an empty `enum`

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.

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.

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 to declare a type that cannot be instantiated.

``````import Foundation

enum NumberFormatterProvider {
static var currencyFormatter: NumberFormatter {
let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.roundingIncrement = 0.01
return formatter
}

static var decimalFormatter: NumberFormatter {
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.decimalSeparator = ","
return formatter
}
}

NumberFormatterProvider() // ❌ impossible to instantiate by mistake

NumberFormatterProvider.currencyFormatter.string(from: 2.456) // \$2.46
NumberFormatterProvider.decimalFormatter.string(from: 2.456) // 2,456
``````

## Using `Never` to represent impossible code paths

`Never` is quite a peculiar type in the Swift Standard Library: it is defined as an empty enum `enum Never { }`.

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).

This way, `Never` can be used as a generic parameter to let the compiler know that a particular feature will not be used.

``````import Foundation

enum Result<Value, Error> {
case success(value: Value)
case failure(error: Error)
}

func willAlwaysSucceed(_ completion: @escaping ((Result<String, Never>) -> Void)) {
completion(.success(value: "Call was successful"))
}

willAlwaysSucceed( { result in
switch result {
case .success(let value):
print(value)
// the compiler knows that the `failure` case cannot happen
// so it doesn't require us to handle it.
}
})
``````

## Providing a default value to a `Decodable``enum`

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.

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.

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:)`:

``````import Foundation

enum State: String, Decodable {
case active
case inactive
case undefined

init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
let decodedString = try container.decode(String.self)

self = State(rawValue: decodedString) ?? .undefined
}
}

let data = """
["active", "inactive", "foo"]
""".data(using: .utf8)!

let decoded = try! JSONDecoder().decode([State].self, from: data)

print(decoded) // [State.active, State.inactive, State.undefined]
``````

## Another lightweight dependency injection through default values for function parameters

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.

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.

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.

``````import Foundation

protocol Service {
func call() -> String
}

class ProductionService: Service {
func call() -> String {
return "This is the production"
}
}

class MockService: Service {
func call() -> String {
return "This is a mock"
}
}

typealias Provider<T> = () -> T

class Controller {

let service: Service

init(serviceProvider: Provider<Service> = { return ProductionService() }) {
self.service = serviceProvider()
}

func work() {
print(service.call())
}
}

let productionController = Controller()
productionController.work() // prints "This is the production"

let mockedController = Controller(serviceProvider: { return MockService() })
mockedController.work() // prints "This is a mock"
``````

## Lightweight dependency injection through protocol-oriented programming

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.

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?

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`.

This way, our code will indeed be decoupled from its dependency, while at the same time keeping the boilerplate to a minimum.

``````import Foundation

protocol Formatting {
var formatter: NumberFormatter { get }
}

private let sharedFormatter: NumberFormatter = {
let sharedFormatter = NumberFormatter()
sharedFormatter.numberStyle = .currency
return sharedFormatter
}()

extension Formatting {
var formatter: NumberFormatter { return sharedFormatter }
}

class ViewModel: Formatting {
var displayableAmount: String?

func updateDisplay(to amount: Double) {
displayableAmount = formatter.string(for: amount)
}
}

let viewModel = ViewModel()

viewModel.updateDisplay(to: 42000.45)
viewModel.displayableAmount // "\$42,000.45"
``````

## Getting rid of overabundant `[weak self]` and `guard`

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.

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.

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!

``````import Foundation
import PlaygroundSupport

PlaygroundPage.current.needsIndefiniteExecution = true

protocol Weakifiable: class { }

extension Weakifiable {
func weakify(_ code: @escaping (Self) -> Void) -> () -> Void {
return { [weak self] in
guard let self = self else { return }

code(self)
}
}

func weakify<T>(_ code: @escaping (T, Self) -> Void) -> (T) -> Void {
return { [weak self] arg in
guard let self = self else { return }

code(arg, self)
}
}
}

extension NSObject: Weakifiable { }

class Producer: NSObject {

deinit {
print("deinit Producer")
}

private var handler: (Int) -> Void = { _ in }

func register(handler: @escaping (Int) -> Void) {
self.handler = handler

DispatchQueue.main.asyncAfter(deadline: .now() + 1.0, execute: { self.handler(42) })
}
}

class Consumer: NSObject {

deinit {
print("deinit Consumer")
}

let producer = Producer()

func consume() {
producer.register(handler: weakify { result, strongSelf in
strongSelf.handle(result)
})
}

private func handle(_ result: Int) {
print("🎉 \(result)")
}
}

var consumer: Consumer? = Consumer()

consumer?.consume()

DispatchQueue.main.asyncAfter(deadline: .now() + 2.0, execute: { consumer = nil })

// This code prints:
// 🎉 42
// deinit Consumer
// deinit Producer
``````

## Solving callback hell with function composition

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.

This often results in callbacks being nested into one another, a predicament often referred to as callback hell.

Many third-party frameworks are able to tackle this issue, for instance RxSwift or 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.

``````import Foundation

typealias CompletionHandler<Result> = (Result?, Error?) -> Void

infix operator ~>: MultiplicationPrecedence

func ~> <T, U>(_ first: @escaping (CompletionHandler<T>) -> Void, _ second: @escaping (T, CompletionHandler<U>) -> Void) -> (CompletionHandler<U>) -> Void {
return { completion in
first({ firstResult, error in
guard let firstResult = firstResult else { completion(nil, error); return }

second(firstResult, { (secondResult, error) in
completion(secondResult, error)
})
})
}
}

func ~> <T, U>(_ first: @escaping (CompletionHandler<T>) -> Void, _ transform: @escaping (T) -> U) -> (CompletionHandler<U>) -> Void {
return { completion in
first({ result, error in
guard let result = result else { completion(nil, error); return }

completion(transform(result), nil)
})
}
}

func service1(_ completionHandler: CompletionHandler<Int>) {
completionHandler(42, nil)
}

func service2(arg: String, _ completionHandler: CompletionHandler<String>) {
completionHandler("🎉 \(arg)", nil)
}

let chainedServices = service1
~> { int in return String(int / 2) }
~> service2

chainedServices({ result, _ in
guard let result = result else { return }

print(result) // Prints: 🎉 21
})
``````

## Transform an asynchronous function into a synchronous one

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.

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.

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.

``````import Foundation

func makeSynchrone<A, B>(_ asyncFunction: @escaping (A, (B) -> Void) -> Void) -> (A) -> B {
return { arg in
let lock = NSRecursiveLock()

var result: B? = nil

asyncFunction(arg) {
result = \$0
lock.unlock()
}

lock.lock()

return result!
}
}

func myAsyncFunction(arg: Int, completionHandler: (String) -> Void) {
completionHandler("🎉 \(arg)")
}

let syncFunction = makeSynchrone(myAsyncFunction)

print(syncFunction(42)) // prints 🎉 42
``````

## Using KeyPaths instead of closures

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()`.

The annoying part is that closures tend to clutter your code with many instances of `{`, `}` and `\$0`, which can quickly undermine its readably.

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.

``````import Foundation

prefix operator ^

prefix func ^ <Element, Attribute>(_ keyPath: KeyPath<Element, Attribute>) -> (Element) -> Attribute {
return { element in element[keyPath: keyPath] }
}

struct MyData {
let int: Int
let string: String
}

let data = [MyData(int: 2, string: "Foo"), MyData(int: 4, string: "Bar")]

data.map(^\.int) // [2, 4]
data.map(^\.string) // ["Foo", "Bar"]
``````

## Bringing some type-safety to a `userInfo``Dictionary`

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]`.

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.

``````import Foundation

typealias TypedUserInfoKey<T> = (key: String, type: T.Type)

extension Dictionary where Key == String, Value == Any {
subscript<T>(_ typedKey: TypedUserInfoKey<T>) -> T? {
return self[typedKey.key] as? T
}
}

let userInfo: [String : Any] = ["Foo": 4, "Bar": "forty-two"]

let integerTypedKey = TypedUserInfoKey(key: "Foo", type: Int.self)
let intValue = userInfo[integerTypedKey] // returns 4
type(of: intValue) // returns Int?

let stringTypedKey = TypedUserInfoKey(key: "Bar", type: String.self)
let stringValue = userInfo[stringTypedKey] // returns "forty-two"
type(of: stringValue) // returns String?
``````

## Lightweight data-binding for an MVVM implementation

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.

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.

For those situation, it's possible to define a lightweight `Variable` type, that will make the MVVM pattern very easy to use!

``````import Foundation

class Variable<Value> {
var value: Value {
didSet {
onUpdate?(value)
}
}

var onUpdate: ((Value) -> Void)? {
didSet {
onUpdate?(value)
}
}

init(_ value: Value, _ onUpdate: ((Value) -> Void)? = nil) {
self.value = value
self.onUpdate = onUpdate
self.onUpdate?(value)
}
}

let variable: Variable<String?> = Variable(nil)

variable.onUpdate = { data in
if let data = data {
print(data)
}
}

variable.value = "Foo"
variable.value = "Bar"

// prints:
// Foo
// Bar
``````

## Using `typealias` to its fullest

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.

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.

``````import Foundation

enum Either<Left, Right> {
case left(Left)
case right(Right)
}

typealias Result<Value> = Either<Value, Error>

typealias IntOrString = Either<Int, String>
``````

## Writing an interruptible overload of `forEach`

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.

Taking inspiration from the Objective-C implementation, we can write an overload that will allow the developer to stop the iteration, if needed.

``````import Foundation

extension Sequence {
func forEach(_ body: (Element, _ stop: inout Bool) throws -> Void) rethrows {
var stop = false
for element in self {
try body(element, &stop)

if stop {
return
}
}
}
}

["Foo", "Bar", "FooBar"].forEach { element, stop in
print(element)
stop = (element == "Bar")
}

// Prints:
// Foo
// Bar
``````

## Optimizing the use of `reduce()`

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.

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.

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.

``````import Foundation

func time(averagedExecutions: Int = 1, _ code: () -> Void) {
let start = Date()
for _ in 0..<averagedExecutions { code() }
let end = Date()

let duration = end.timeIntervalSince(start) / Double(averagedExecutions)

print("time: \(duration)")
}

let data = (1...1_000).map { _ in Int(arc4random_uniform(256)) }

// runs in 0.63s
time {
let noDuplicates: [Int] = data.reduce([], { \$0.contains(\$1) ? \$0 : \$0 + [\$1] })
}

// runs in 0.15s
time {
let noDuplicates: [Int] = data.reduce(into: [], { if !\$0.contains(\$1) { \$0.append(\$1) } } )
}
``````

## Avoiding hardcoded reuse identifiers

UI components such as `UITableView` and `UICollectionView` rely on reuse identifiers in order to efficiently recycle the views they display. Often, those reuse identifiers take the form of a static hardcoded `String`, that will be used for every instance of their class.

Through protocol-oriented programing, it's possible to avoid those hardcoded values, and instead use the name of the type as a reuse identifier.

``````import Foundation
import UIKit

protocol Reusable {
static var reuseIdentifier: String { get }
}

extension Reusable {
static var reuseIdentifier: String {
return String(describing: self)
}
}

extension UITableViewCell: Reusable { }

extension UITableView {
func register<T: UITableViewCell>(_ class: T.Type) {
register(`class`, forCellReuseIdentifier: T.reuseIdentifier)
}
func dequeueReusableCell<T: UITableViewCell>(for indexPath: IndexPath) -> T {
return dequeueReusableCell(withIdentifier: T.reuseIdentifier, for: indexPath) as! T
}
}

class MyCell: UITableViewCell { }

let tableView = UITableView()

tableView.register(MyCell.self)
let myCell: MyCell = tableView.dequeueReusableCell(for: [0, 0])
``````

## Defining a union type

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.

``````import Foundation

enum Either<A, B> {
case left(A)
case right(B)

func either(ifLeft: ((A) -> Void)? = nil, ifRight: ((B) -> Void)? = nil) {
switch self {
case let .left(a):
ifLeft?(a)
case let .right(b):
ifRight?(b)
}
}
}

extension Bool { static func random() -> Bool { return arc4random_uniform(2) == 0 } }

var intOrString: Either<Int, String> = Bool.random() ? .left(2) : .right("Foo")

intOrString.either(ifLeft: { print(\$0 + 1) }, ifRight: { print(\$0 + "Bar") })
``````

If you're interested by this kind of data structure, I strongly recommend that you learn more about Algebraic Data Types.

## Asserting that classes have associated NIBs and vice-versa

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`.

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.

``````import XCTest

public func XCTAssertClassHasNib(_ class: AnyClass, bundle: Bundle, file: StaticString = #file, line: UInt = #line) {
let associatedNibURL = bundle.url(forResource: String(describing: `class`), withExtension: "nib")

XCTAssertNotNil(associatedNibURL, "Class \"\(`class`)\" has no associated nib file", file: file, line: line)
}

public func XCTAssertNibHaveClasses(_ bundle: Bundle, file: StaticString = #file, line: UInt = #line) {
guard let bundleName = bundle.infoDictionary?["CFBundleName"] as? String,
let basePath = bundle.resourcePath,
let enumerator = FileManager.default.enumerator(at: URL(fileURLWithPath: basePath),
includingPropertiesForKeys: nil,
options: [.skipsHiddenFiles, .skipsSubdirectoryDescendants]) else { return }

var nibFilesURLs = [URL]()

for case let fileURL as URL in enumerator {
if fileURL.pathExtension.uppercased() == "NIB" {
nibFilesURLs.append(fileURL)
}
}

nibFilesURLs.map { \$0.lastPathComponent }
.compactMap { \$0.split(separator: ".").first }
.map { String(\$0) }
.forEach {
let associatedClass: AnyClass? = bundle.classNamed("\(bundleName).\(\$0)")

XCTAssertNotNil(associatedClass, "File \"\(\$0).nib\" has no associated class", file: file, line: line)
}
}

XCTAssertClassHasNib(MyFirstTableViewCell.self, bundle: Bundle(for: AppDelegate.self))
XCTAssertClassHasNib(MySecondTableViewCell.self, bundle: Bundle(for: AppDelegate.self))

XCTAssertNibHaveClasses(Bundle(for: AppDelegate.self))
``````

Many thanks Benjamin Lavialle for coming up with the idea behind the second test predicate.

## Small footprint type-erasing with functions

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.

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.

``````import Foundation
import UIKit

protocol Configurable {
associatedtype Model

func configure(with model: Model)
}

typealias Configurator<Model> = (Model) -> ()

extension UILabel: Configurable {
func configure(with model: String) {
self.text = model
}
}

let label = UILabel()
let configurator: Configurator<String> = label.configure

configurator("Foo")

label.text // "Foo"
``````

## Performing animations sequentially

`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.

Nonetheless, it's possible to define a rather simple class, that will expose a really nicer API for this particular use case 👌

``````import Foundation
import UIKit

class AnimationSequence {
typealias Animations = () -> Void

private let current: Animations
private let duration: TimeInterval
private var next: AnimationSequence? = nil

init(animations: @escaping Animations, duration: TimeInterval) {
self.current = animations
self.duration = duration
}

@discardableResult func append(animations: @escaping Animations, duration: TimeInterval) -> AnimationSequence {
var lastAnimation = self
while let nextAnimation = lastAnimation.next {
lastAnimation = nextAnimation
}
lastAnimation.next = AnimationSequence(animations: animations, duration: duration)
return self
}

func run() {
UIView.animate(withDuration: duration, animations: current, completion: { finished in
if finished, let next = self.next {
next.run()
}
})
}
}

var firstView = UIView()
var secondView = UIView()

firstView.alpha = 0
secondView.alpha = 0

AnimationSequence(animations: { firstView.alpha = 1.0 }, duration: 1)
.append(animations: { secondView.alpha = 1.0 }, duration: 0.5)
.append(animations: { firstView.alpha = 0.0 }, duration: 2.0)
.run()
``````

## Debouncing a function call

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.

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.

``````import Foundation

func debounced(delay: TimeInterval, queue: DispatchQueue = .main, action: @escaping (() -> Void)) -> () -> Void {
var workItem: DispatchWorkItem?

return {
workItem?.cancel()
workItem = DispatchWorkItem(block: action)
queue.asyncAfter(deadline: .now() + delay, execute: workItem!)
}
}

let debouncedPrint = debounced(delay: 1.0) { print("Action performed!") }

debouncedPrint()
debouncedPrint()
debouncedPrint()

// After a 1 second delay, this gets
// printed only once to the console:

// Action performed!
``````

## Providing useful operators for `Optional` booleans

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, we can define a couple operators that make working with `Bool?` values much nicer.

``````import Foundation

func && (lhs: Bool?, rhs: Bool?) -> Bool? {
switch (lhs, rhs) {
case (false, _), (_, false):
return false
case let (unwrapLhs?, unwrapRhs?):
return unwrapLhs && unwrapRhs
default:
return nil
}
}

func || (lhs: Bool?, rhs: Bool?) -> Bool? {
switch (lhs, rhs) {
case (true, _), (_, true):
return true
case let (unwrapLhs?, unwrapRhs?):
return unwrapLhs || unwrapRhs
default:
return nil
}
}

false && nil // false
true && nil // nil
[true, nil, false].reduce(true, &&) // false

nil || true // true
nil || false // nil
[true, nil, false].reduce(false, ||) // true
``````

## Removing duplicate values from a `Sequence`

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:

``````import Foundation

extension Sequence where Element: Equatable {
func duplicatesRemoved() -> [Element] {
return reduce([], { \$0.contains(\$1) ? \$0 : \$0 + [\$1] })
}
}

let data = [2, 5, 2, 3, 6, 5, 2]

data.duplicatesRemoved() // [2, 5, 3, 6]
``````

## Shorter syntax to deal with optional strings

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.

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.

``````import Foundation
import UIKit

extension Optional where Wrapped == String {
var orEmpty: String {
switch self {
case .some(let value):
return value
case .none:
return ""
}
}
}

func doesNotWorkWithOptionalString(_ param: String) {
// do something with `param`
}

let label = UILabel()
label.text = "This is some text."

doesNotWorkWithOptionalString(label.text.orEmpty)
``````

## Encapsulating background computation and UI update

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.

Still, running a costly computation on the background, and then using it to update the UI can be a common pattern.

In such cases you can rely on `asyncUI` to encapsulate all the boilerplate code.

``````import Foundation
import UIKit

func asyncUI<T>(_ computation: @autoclosure @escaping () -> T, qos: DispatchQoS.QoSClass = .userInitiated, _ completion: @escaping (T) -> Void) {
DispatchQueue.global(qos: qos).async {
let value = computation()
DispatchQueue.main.async {
completion(value)
}
}
}

let label = UILabel()

func costlyComputation() -> Int { return (0..<10_000).reduce(0, +) }

asyncUI(costlyComputation()) { value in
label.text = "\(value)"
}
``````

## Retrieving all the necessary data to build a debug view

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 🍰

``````import Foundation
import UIKit
import ObjectiveC

extension Bundle {
func viewControllerTypes() -> [UIViewController.Type] {
guard let bundlePath = self.executablePath else { return [] }

var size: UInt32 = 0
var rawClassNames: UnsafeMutablePointer<UnsafePointer<Int8>>!
var parsedClassNames = [String]()

rawClassNames = objc_copyClassNamesForImage(bundlePath, &size)

for index in 0..<size {
let className = rawClassNames[Int(index)]

if let name = NSString.init(utf8String:className) as String?,
NSClassFromString(name) is UIViewController.Type {
parsedClassNames.append(name)
}
}

return parsedClassNames
.sorted()
.compactMap { NSClassFromString(\$0) as? UIViewController.Type }
}
}

// Fetch all view controller types in UIKit
Bundle(for: UIViewController.self).viewControllerTypes()
``````

I share the credit for this tip with Benoît Caron.

## Defining a function to map over dictionaries

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 of a real `map` function.

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.

``````import Foundation

extension Dictionary {
func map<T: Hashable, U>(_ transform: (Key, Value) throws -> (T, U)) rethrows -> [T: U] {
var result: [T: U] = [:]

for (key, value) in self {
let (transformedKey, transformedValue) = try transform(key, value)
result[transformedKey] = transformedValue
}

return result
}
}

let data = [0: 5, 1: 6, 2: 7]
data.map { ("\(\$0)", \$1 * \$1) } // ["2": 49, "0": 25, "1": 36]
``````

## A shorter syntax to remove `nil` values

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.

The implementation isn't as straightforward as your usual `extension`, but once it has been written, the call site definitely gets cleaner 👌

``````import Foundation

protocol OptionalConvertible {
associatedtype Wrapped
func asOptional() -> Wrapped?
}

extension Optional: OptionalConvertible {
func asOptional() -> Wrapped? {
return self
}
}

extension Sequence where Element: OptionalConvertible {
func compacted() -> [Element.Wrapped] {
return compactMap { \$0.asOptional() }
}
}

let data = [nil, 1, 2, nil, 3, 5, nil, 8, nil]
data.compacted() // [1, 2, 3, 5, 8]
``````

## Dealing with expirable values

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.

``````import Foundation

struct Expirable<T> {
private var innerValue: T
private(set) var expirationDate: Date

var value: T? {
return hasExpired() ? nil : innerValue
}

init(value: T, expirationDate: Date) {
self.innerValue = value
self.expirationDate = expirationDate
}

init(value: T, duration: Double) {
self.innerValue = value
}

func hasExpired() -> Bool {
return expirationDate < Date()
}
}

let expirable = Expirable(value: 42, duration: 3)

sleep(2)
expirable.value // 42
sleep(2)
expirable.value // nil
``````

I share the credit for this tip with Benoît Caron.

## Using parallelism to speed-up `map()`

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.

``````import Foundation

extension Array {
func parallelMap<T>(_ transform: (Element) -> T) -> [T] {
let res = UnsafeMutablePointer<T>.allocate(capacity: count)

DispatchQueue.concurrentPerform(iterations: count) { i in
res[i] = transform(self[i])
}

let finalResult = Array<T>(UnsafeBufferPointer(start: res, count: count))
res.deallocate(capacity: count)

return finalResult
}
}

let array = (0..<1_000).map { \$0 }

func work(_ n: Int) -> Int {
return (0..<n).reduce(0, +)
}

array.parallelMap { work(\$0) }
``````

🚨 Make sure to only use `parallelMap()` when the `transform` function actually performs some costly computations. Otherwise performances will be systematically slower than using `map()`, because of the multithreading overhead.

## Measuring execution time with minimum boilerplate

During development of a feature that performs some heavy computations, it can be helpful to measure just how much time a chunk of code takes to run. The `time()` function is a nice tool for this purpose, because of how simple it is to add and then to remove when it is no longer needed.

``````import Foundation

func time(averagedExecutions: Int = 1, _ code: () -> Void) {
let start = Date()
for _ in 0..<averagedExecutions { code() }
let end = Date()

let duration = end.timeIntervalSince(start) / Double(averagedExecutions)

print("time: \(duration)")
}

time {
(0...10_000).map { \$0 * \$0 }
}
// time: 0.183973908424377
``````

## Running two pieces of code in parallel

Concurrency is definitely one of those topics were the right encapsulation bears the potential to make your life so much easier. For instance, with this piece of code you can easily launch two computations in parallel, and have the results returned in a tuple.

``````import Foundation

func parallel<T, U>(_ left: @autoclosure () -> T, _ right: @autoclosure () -> U) -> (T, U) {
var leftRes: T?
var rightRes: U?

DispatchQueue.concurrentPerform(iterations: 2, execute: { id in
if id == 0 {
leftRes = left()
} else {
rightRes = right()
}
})

return (leftRes!, rightRes!)
}

let values = (1...100_000).map { \$0 }

let results = parallel(values.map { \$0 * \$0 }, values.reduce(0, +))
``````

## Making good use of #file, #line and #function

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.

``````import Foundation

func log(_ message: String, _ file: String = #file, _ line: Int = #line, _ function: String = #function) {
print("[\(file):\(line)] \(function) - \(message)")
}

func foo() {
log("Hello world!")
}

foo() // [MyPlayground.playground:8] foo() - Hello world!
``````

## Comparing Optionals through Conditional Conformance

Swift 4.1 has introduced a new feature called Conditional Conformance, which allows a type to implement a protocol only when its generic type also does.

With this addition it becomes easy to let `Optional` implement `Comparable` only when `Wrapped` also implements `Comparable`:

``````import Foundation

extension Optional: Comparable where Wrapped: Comparable {
public static func < (lhs: Optional, rhs: Optional) -> Bool {
switch (lhs, rhs) {
case let (lhs?, rhs?):
return lhs < rhs
case (nil, _?):
return true // anything is greater than nil
case (_?, nil):
return false // nil in smaller than anything
case (nil, nil):
return true // nil is not smaller than itself
}
}
}

let data: [Int?] = [8, 4, 3, nil, 12, 4, 2, nil, -5]
data.sorted() // [nil, nil, Optional(-5), Optional(2), Optional(3), Optional(4), Optional(4), Optional(8), Optional(12)]
``````

## Safely subscripting a Collection

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.

A great thing is that this condition can be encapsulated in a custom `subscript` that will work on any `Collection`:

``````import Foundation

extension Collection {
subscript (safe index: Index) -> Element? {
return indices.contains(index) ? self[index] : nil
}
}

let data = [1, 3, 4]

data[safe: 1] // Optional(3)
data[safe: 10] // nil
``````

## Easier String slicing using ranges

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)..<index(startIndex, offsetBy: 10)]` on a regular basis.

Luckily, with the addition of one clever extension, strings can be sliced as easily as arrays 🎉

``````import Foundation

extension String {
public subscript(value: CountableClosedRange<Int>) -> Substring {
get {
return self[index(startIndex, offsetBy: value.lowerBound)...index(startIndex, offsetBy: value.upperBound)]
}
}

public subscript(value: CountableRange<Int>) -> Substring {
get {
return self[index(startIndex, offsetBy: value.lowerBound)..<index(startIndex, offsetBy: value.upperBound)]
}
}

public subscript(value: PartialRangeUpTo<Int>) -> Substring {
get {
return self[..<index(startIndex, offsetBy: value.upperBound)]
}
}

public subscript(value: PartialRangeThrough<Int>) -> Substring {
get {
return self[...index(startIndex, offsetBy: value.upperBound)]
}
}

public subscript(value: PartialRangeFrom<Int>) -> Substring {
get {
return self[index(startIndex, offsetBy: value.lowerBound)...]
}
}
}

let data = "This is a string!"

data[..<4]  // "This"
data[5..<9] // "is a"
data[10...] // "string!"
``````

## Concise syntax for sorting using a KeyPath

By using a `KeyPath` along with a generic type, a very clean and concise syntax for sorting data can be implemented:

``````import Foundation

extension Sequence {
func sorted<T: Comparable>(by attribute: KeyPath<Element, T>) -> [Element] {
return sorted(by: { \$0[keyPath: attribute] < \$1[keyPath: attribute] })
}
}

let data = ["Some", "words", "of", "different", "lengths"]

data.sorted(by: \.count) // ["of", "Some", "words", "lengths", "different"]
``````

If you like this syntax, make sure to checkout KeyPathKit!

## Manufacturing cache-efficient versions of pure functions

By capturing a local variable in a returned closure, it is possible to manufacture cache-efficient versions of pure functions. Be careful though, this trick only works with non-recursive function!

``````import Foundation

func cached<In: Hashable, Out>(_ f: @escaping (In) -> Out) -> (In) -> Out {
var cache = [In: Out]()

return { (input: In) -> Out in
if let cachedValue = cache[input] {
return cachedValue
} else {
let result = f(input)
cache[input] = result
return result
}
}
}

let cachedCos = cached { (x: Double) in cos(x) }

cachedCos(.pi * 2) // value of cos for 2π is now cached
``````

## Simplifying complex conditions with pattern matching

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 {}`.

``````import Foundation

let expr1: Bool
let expr2: Bool
let expr3: Bool

if expr1 && !expr3 {
functionA()
} else if !expr2 && expr3 {
functionB()
} else if expr1 && !expr2 && expr3 {
functionC()
}

switch (expr1, expr2, expr3) {

case (true, _, false):
functionA()
case (_, false, true):
functionB()
case (true, false, true):
functionC()
default:
break
}
``````

## Easily generating arrays of data

Using `map()` on a range makes it easy to generate an array of data.

``````import Foundation

func randomInt() -> Int { return Int(arc4random()) }

let randomArray = (1...10).map { _ in randomInt() }
``````

## Using @autoclosure for cleaner call sites

Using `@autoclosure` enables the compiler to automatically wrap an argument within a closure, thus allowing for a very clean syntax at call sites.

``````import UIKit

extension UIView {
class func animate(withDuration duration: TimeInterval, _ animations: @escaping @autoclosure () -> Void) {
UIView.animate(withDuration: duration, animations: animations)
}
}

let view = UIView()

UIView.animate(withDuration: 0.3, view.backgroundColor = .orange)
``````

## Observing new and old value with RxSwift

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()`.

``````import RxSwift

let values = Observable.of(4, 8, 15, 16, 23, 42)

let newAndOld = Observable.zip(values, values.skip(1)) { (previous: \$0, current: \$1) }
.subscribe(onNext: { pair in
print("current: \(pair.current) - previous: \(pair.previous)")
})

//current: 8 - previous: 4
//current: 15 - previous: 8
//current: 16 - previous: 15
//current: 23 - previous: 16
//current: 42 - previous: 23
``````

## Implicit initialization from literal values

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.

``````import Foundation

extension URL: ExpressibleByStringLiteral {
public init(stringLiteral value: String) {
self.init(string: value)!
}
}

``````

## Achieving systematic validation of data

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.

``````import Foundation

struct Untrusted<T> {
private(set) var value: T
}

protocol Validator {
associatedtype T
static func validation(value: T) -> Bool
}

extension Validator {
static func validate(untrusted: Untrusted<T>) -> T? {
if self.validation(value: untrusted.value) {
return untrusted.value
} else {
return nil
}
}
}

struct FrenchPhoneNumberValidator: Validator {
static func validation(value: String) -> Bool {
return (value.count) == 10 && CharacterSet(charactersIn: value).isSubset(of: CharacterSet.decimalDigits)
}
}

let validInput = Untrusted(value: "0122334455")
let invalidInput = Untrusted(value: "0123")

FrenchPhoneNumberValidator.validate(untrusted: validInput) // returns "0122334455"
FrenchPhoneNumberValidator.validate(untrusted: invalidInput) // returns nil
``````

## Implementing the builder pattern with keypaths

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.

``````import UIKit

protocol With {}

extension With where Self: AnyObject {
func with<T>(_ property: ReferenceWritableKeyPath<Self, T>, setTo value: T) -> Self {
self[keyPath: property] = value
return self
}
}

extension UIView: With {}

let view = UIView()

let label = UILabel()
.with(\.textColor, setTo: .red)
.with(\.text, setTo: "Foo")
.with(\.textAlignment, setTo: .right)

``````

🚨 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.

I share the credit for this tip with Marion Curtil.

## Storing functions rather than values

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.

``````import Foundation

struct MaxValidator {
let max: Int
let strictComparison: Bool

func isValid(_ value: Int) -> Bool {
return self.strictComparison ? value < self.max : value <= self.max
}
}

struct MaxValidator2 {
var isValid: (_ value: Int) -> Bool

init(max: Int, strictComparison: Bool) {
self.isValid = strictComparison ? { \$0 < max } : { \$0 <= max }
}
}

MaxValidator(max: 5, strictComparison: true).isValid(5) // false
MaxValidator2(max: 5, strictComparison: false).isValid(5) // true
``````

## Defining operators on function types

Functions are first-class citizen types in Swift, so it is perfectly legal to define operators for them.

``````import Foundation

let firstRange = { (0...3).contains(\$0) }
let secondRange = { (5...6).contains(\$0) }

func ||(_ lhs: @escaping (Int) -> Bool, _ rhs: @escaping (Int) -> Bool) -> (Int) -> Bool {
return { value in
return lhs(value) || rhs(value)
}
}

(firstRange || secondRange)(2) // true
(firstRange || secondRange)(4) // false
(firstRange || secondRange)(6) // true
``````

## Typealiases for functions

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.

``````import Foundation

typealias RangeSet = (Int) -> Bool

func union(_ left: @escaping RangeSet, _ right: @escaping RangeSet) -> RangeSet {
return { left(\$0) || right(\$0) }
}

let firstRange = { (0...3).contains(\$0) }
let secondRange = { (5...6).contains(\$0) }

let unionRange = union(firstRange, secondRange)

unionRange(2) // true
unionRange(4) // false
``````

## Encapsulating state within a function

By returning a closure that captures a local variable, it's possible to encapsulate a mutable state within a function.

``````import Foundation

func counterFactory() -> () -> Int {
var counter = 0

return {
counter += 1
return counter
}
}

let counter = counterFactory()

counter() // returns 1
counter() // returns 2
``````

## Generating all cases for an Enum

⚠️ 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.

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.

``````import Foundation

enum MyEnum { case first; case second; case third; case fourth }

protocol EnumCollection: Hashable {
static var allCases: [Self] { get }
}

extension EnumCollection {
public static var allCases: [Self] {
var i = 0
return Array(AnyIterator {
let next = withUnsafePointer(to: &i) {
\$0.withMemoryRebound(to: Self.self, capacity: 1) { \$0.pointee }
}
if next.hashValue != i { return nil }
i += 1
return next
})
}
}

extension MyEnum: EnumCollection { }

MyEnum.allCases // [.first, .second, .third, .fourth]
``````

## Using map on optional values

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.

``````import UIKit

let date: Date? = Date() // or could be nil, doesn't matter
let formatter = DateFormatter()
let label = UILabel()

if let safeDate = date {
label.text = formatter.string(from: safeDate)
}

label.text = date.map { return formatter.string(from: \$0) }

label.text = date.map(formatter.string(from:)) // even shorter, tough less readable
``````

📣 NEW 📣 Swift Tips are now available on YouTube 👇

Summary

Tips

#swift

1594740720

## Graphical Functions made from an effortless sketch

Hello everyone! A few days ago, I was working on a machine learning model where I needed to input a function relating X and Y. The only constraints were that the function had to be continuous and the bounds for X and Y had to be [0, 1].

With dozens of distinct curves in mind, I started to sketch them out on a paper. The point was to fit them on a graphing calculator afterwards. It was a tedious task and I asked my sister for help.

“Why don’t you write a program for it?”, she replied.

# Purpose

An existing application: MyCurveFit

There are existing applications that take in X and Y coordinates to return the exact equation. However, the more complex the curve is, the more coordinates the user has to key in. Furthermore, the user has to manually choose the function to fit the points (Example: Linear versus Exponential).

#python #scipy #mathematics #functions