1585191540

# Golang Tutorial - Functions in Golang

Functions in Golang are very clean. You will surely avoid a lot of common errors while defining functions in golang.

A function is an independent section of code that maps zero or more input parameters to zero or more output parameters. Functions (also known as procedures or subroutines) are often represented as a black box: (the black box represents the function)

Until now the programs we have written in Go have used only one function:

``````func main() {}
``````

We will now begin writing programs that use more than one function.

``````func main() {
xs := []float64{98,93,77,82,83}

total := 0.0
for _, v := range xs {
total += v
}
fmt.Println(total / float64(len(xs)))
}
``````

This program computes the average of a series of numbers. Finding the average like this is a very general problem, so it’s an ideal candidate for definition as a function.

The `average` function will need to take in a slice of `float64`s and return one `float64`. Insert this before the `main` function:

``````func average(xs []float64) float64 {
panic("Not Implemented")
}
``````

Functions start with the keyword `func`, followed by the function’s name. The parameters (inputs) of the function are defined like this: `name type, name type, …`. Our function has one parameter (the list of scores) that we named `xs`. After the parameters we put the return type. Collectively the parameters and the return type are known as the function’s signature.

Finally we have the function body which is a series of statements between curly braces. In this body we invoke a built-in function called `panic` which causes a run time error. (We’ll see more about panic later in this chapter) Writing functions can be difficult so it’s a good idea to break the process into manageable chunks, rather than trying to implement the entire thing in one large step.

Now let’s take the code from our main function and move it into our average function:

``````func average(xs []float64) float64 {
total := 0.0
for _, v := range xs {
total += v
}
}
``````

Notice that we changed the `fmt.Println` to be a `return` instead. The return statement causes the function to immediately stop and return the value after it to the function that called this one. Modify `main` to look like this:

``````func main() {
xs := []float64{98,93,77,82,83}
fmt.Println(average(xs))
}
``````

Running this program should give you exactly the same result as the original. A few things to keep in mind:

• The names of the parameters don’t have to match in the calling function. For example we could have done this:
``````func main() {
someOtherName := []float64{98,93,77,82,83}
fmt.Println(average(someOtherName))
}
``````

And our program would still work.

• Functions don’t have access to anything in the calling function. This won’t work:
``````func f() {
fmt.Println(x)
}
func main() {
x := 5
f()
}
``````

We need to either do this:

``````func f(x int) {
fmt.Println(x)
}
func main() {
x := 5
f(x)
}
``````

Or this:

``````var x int = 5
func f() {
fmt.Println(x)
}
func main() {
f()
}
``````
• Functions are built up in a “stack”. Suppose we had this program:
``````func main() {
fmt.Println(f1())
}
func f1() int {
return f2()
}
func f2() int {
return 1
}
``````
• We could visualize it like this:

Each time we call a function we push it onto the call stack and each time we return from a function we pop the last function off of the stack.

• We can also name the return type:
``````func f2() (r int) {
r = 1
return
}
``````

## Returning Multiple Values

Go is also capable of returning multiple values from a function:

``````func f() (int, int) {
return 5, 6
}

func main() {
x, y := f()
}
``````

Three changes are necessary: change the return type to contain multiple types separated by `,`, change the expression after the return so that it contains multiple expressions separated by `,` and finally change the assignment statement so that multiple values are on the left side of the `:=` or `=`.

Multiple values are often used to return an error value along with the result (`x, err := f()`), or a boolean to indicate success (`x, ok := f()`).

There is a special form available for the last parameter in a Go function:

``````func add(args ...int) int {
total := 0
for _, v := range args {
total += v
}
}
func main() {
}
``````

By using `...` before the type name of the last parameter you can indicate that it takes zero or more of those parameters. In this case we take zero or more `int`s. We invoke the function like any other function except we can pass as many `int`s as we want.

This is precisely how the `fmt.Println` function is implemented:

``````func Println(a ...interface{}) (n int, err error)
``````

The `Println` function takes any number of values of any type. (The special `interface{}` type will be discussed in more detail in chapter 9)

We can also pass a slice of `int`s by following the slice with `...`:

``````func main() {
xs := []int{1,2,3}
}
``````

## Closure

It is possible to create functions inside of functions:

``````func main() {
add := func(x, y int) int {
return x + y
}
}
``````

`add` is a local variable that has the type `func(int, int) int` (a function that takes two `int`s and returns an `int`). When you create a local function like this it also has access to other local variables:

``````func main() {
x := 0
increment := func() int {
x++
return x
}
fmt.Println(increment())
fmt.Println(increment())
}
``````

`increment` adds 1 to the variable `x` which is defined in the `main` function’s scope. This `x` variable can be accessed and modified by the `increment` function. This is why the first time we call `increment` we see 1 displayed, but the second time we call it we see 2 displayed.

A function like this together with the non-local variables it references is known as a closure. In this case `increment` and the variable `x` form the closure.

One way to use closure is by writing a function which returns another function which – when called – can generate a sequence of numbers. For example here’s how we might generate all the even numbers:

``````func makeEvenGenerator() func() uint {
i := uint(0)
return func() (ret uint) {
ret = i
i += 2
return
}
}
func main() {
nextEven := makeEvenGenerator()
fmt.Println(nextEven()) // 0
fmt.Println(nextEven()) // 2
fmt.Println(nextEven()) // 4
}
``````

`makeEvenGenerator` returns a function which generates even numbers. Each time it’s called it adds 2 to the local `i` variable which – unlike normal local variables – persists between calls.

## Recursion

Finally a function is able to call itself. Here is one way to compute the factorial of a number:

``````func factorial(x uint) uint {
if x == 0 {
return 1
}
return x * factorial(x-1)
}
``````

`factorial` calls itself, which is what makes this function recursive. In order to better understand how this function works, lets walk through `factorial(2)`:

• Is `x == 0`? No. (`x` is 2)

• Find the factorial of `x – 1`

• Is `x == 0`? No. (`x` is 1)

• Find the `factorial` of `x – 1`

• Is `x == 0`? Yes, return 1.
• return `1 * 1`

• return `2 * 1`

Closure and recursion are powerful programming techniques which form the basis of a paradigm known as functional programming. Most people will find functional programming more difficult to understand than an approach based on for loops, if statements, variables and simple functions.

## Defer, Panic & Recover

Go has a special statement called `defer` which schedules a function call to be run after the function completes. Consider the following example:

``````package main

import "fmt"

func first() {
fmt.Println("1st")
}
func second() {
fmt.Println("2nd")
}
func main() {
defer second()
first()
}
``````

This program prints `1st` followed by `2nd`. Basically defer moves the call to `second` to the end of the function:

``````func main() {
first()
second()
}
``````

`defer` is often used when resources need to be freed in some way. For example when we open a file we need to make sure to close it later. With `defer`:

``````f, _ := os.Open(filename)
defer f.Close()
``````

This has 3 advantages: (1) it keeps our `Close` call near our `Open` call so it’s easier to understand, (2) if our function had multiple return statements (perhaps one in an `if` and one in an `else`) `Close` will happen before both of them and (3) deferred functions are run even if a run-time panic occurs.

### Panic & Recover

Earlier we created a function that called the `panic` function to cause a run time error. We can handle a run-time panic with the built-in `recover` function. `recover` stops the panic and returns the value that was passed to the call to `panic`. We might be tempted to use it like this:

``````package main

import "fmt"

func main() {
panic("PANIC")
str := recover()
fmt.Println(str)
}
``````

But the call to `recover` will never happen in this case because the call to `panic` immediately stops execution of the function. Instead we have to pair it with `defer`:

``````package main

import "fmt"

func main() {
defer func() {
str := recover()
fmt.Println(str)
}()
panic("PANIC")
}
``````

A panic generally indicates a programmer error (for example attempting to access an index of an array that’s out of bounds, forgetting to initialize a map, etc.) or an exceptional condition that there’s no easy way to recover from. (Hence the name “panic”)

### Problems

• `sum` is a function which takes a slice of numbers and adds them together. What would its function signature look like in Go?

• Write a function which takes an integer and halves it and returns true if it was even or false if it was odd. For example `half(1)` should return `(0, false)` and `half(2)` should return `(1, true)`.

• Write a function with one variadic parameter that finds the greatest number in a list of numbers.

• Using `makeEvenGenerator` as an example, write a `makeOddGenerator` function that generates odd numbers.

• The Fibonacci sequence is defined as: `fib(0) = 0`, `fib(1) = 1`, `fib(n) = fib(n-1) + fib(n-2)`. Write a recursive function which can find `fib(n)`.

• What are defer, panic and recover? How do you recover from a run-time panic?

#go #golang

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

1596728880

## Tutorial: Getting Started with R and RStudio

In this tutorial we’ll learn how to begin programming with R using RStudio. We’ll install R, and RStudio RStudio, an extremely popular development environment for R. We’ll learn the key RStudio features in order to start programming in R on our own.

If you already know how to use RStudio and want to learn some tips, tricks, and shortcuts, check out this Dataquest blog post.

#data science tutorials #beginner #r tutorial #r tutorials #rstats #tutorial #tutorials

1596513720

## 1. Characteristics of Clean Data and Messy Data

What exactly is clean data? Clean data is accurate, complete, and in a format that is ready to analyze. Characteristics of clean data include data that are:

• Free of duplicate rows/values
• Error-free (e.g. free of misspellings)
• Relevant (e.g. free of special characters)
• The appropriate data type for analysis
• Free of outliers (or only contain outliers have been identified/understood), and
• Follows a “tidy data” structure

Common symptoms of messy data include data that contain:

• Special characters (e.g. commas in numeric values)
• Numeric values stored as text/character data types
• Duplicate rows
• Misspellings
• Inaccuracies
• White space
• Missing data
• Zeros instead of null values

## 2. Motivation

In this blog post, we will work with five property-sales datasets that are publicly available on the New York City Department of Finance Rolling Sales Data website. We encourage you to download the datasets and follow along! Each file contains one year of real estate sales data for one of New York City’s five boroughs. We will work with the following Microsoft Excel files:

• rollingsales_bronx.xls
• rollingsales_brooklyn.xls
• rollingsales_manhattan.xls
• rollingsales_queens.xls
• rollingsales_statenisland.xls

As we work through this blog post, imagine that you are helping a friend launch their home-inspection business in New York City. You offer to help them by analyzing the data to better understand the real-estate market. But you realize that before you can analyze the data in R, you will need to diagnose and clean it first. And before you can diagnose the data, you will need to load it into R!

Benefits of using tidyverse tools are often evident in the data-loading process. In many cases, the tidyverse package `readxl` will clean some data for you as Microsoft Excel data is loaded into R. If you are working with CSV data, the tidyverse `readr` package function `read_csv()` is the function to use (we’ll cover that later).

Let’s look at an example. Here’s how the Excel file for the Brooklyn borough looks:

The Brooklyn Excel file

Now let’s load the Brooklyn dataset into R from an Excel file. We’ll use the `readxl`package. We specify the function argument `skip = 4` because the row that we want to use as the header (i.e. column names) is actually row 5. We can ignore the first four rows entirely and load the data into R beginning at row 5. Here’s the code:

``````library(readxl) # Load Excel files
brooklyn <- read_excel("rollingsales_brooklyn.xls", skip = 4)
``````

Note we saved this dataset with the variable name `brooklyn` for future use.

## 4. View the Data with tidyr::glimpse()

The tidyverse offers a user-friendly way to view this data with the `glimpse()` function that is part of the `tibble` package. To use this package, we will need to load it for use in our current session. But rather than loading this package alone, we can load many of the tidyverse packages at one time. If you do not have the tidyverse collection of packages, install it on your machine using the following command in your R or R Studio session:

``````install.packages("tidyverse")
``````

Once the package is installed, load it to memory:

``````library(tidyverse)
``````

Now that `tidyverse` is loaded into memory, take a “glimpse” of the Brooklyn dataset:

``````glimpse(brooklyn)
## Observations: 20,185
## Variables: 21
## \$ BOROUGH <chr> "3", "3", "3", "3", "3", "3", "…
## \$ NEIGHBORHOOD <chr> "BATH BEACH", "BATH BEACH", "BA…
## \$ `BUILDING CLASS CATEGORY` <chr> "01 ONE FAMILY DWELLINGS", "01 …
## \$ `TAX CLASS AT PRESENT` <chr> "1", "1", "1", "1", "1", "1", "…
## \$ BLOCK <dbl> 6359, 6360, 6364, 6367, 6371, 6…
## \$ LOT <dbl> 70, 48, 74, 24, 19, 32, 65, 20,…
## \$ `EASE-MENT` <lgl> NA, NA, NA, NA, NA, NA, NA, NA,…
## \$ `BUILDING CLASS AT PRESENT` <chr> "S1", "A5", "A5", "A9", "A9", "…
## \$ ADDRESS <chr> "8684 15TH AVENUE", "14 BAY 10T…
## \$ `APARTMENT NUMBER` <chr> NA, NA, NA, NA, NA, NA, NA, NA,…
## \$ `ZIP CODE` <dbl> 11228, 11228, 11214, 11214, 112…
## \$ `RESIDENTIAL UNITS` <dbl> 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1…
## \$ `COMMERCIAL UNITS` <dbl> 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0…
## \$ `TOTAL UNITS` <dbl> 2, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1…
## \$ `LAND SQUARE FEET` <dbl> 1933, 2513, 2492, 1571, 2320, 3…
## \$ `GROSS SQUARE FEET` <dbl> 4080, 1428, 972, 1456, 1566, 22…
## \$ `YEAR BUILT` <dbl> 1930, 1930, 1950, 1935, 1930, 1…
## \$ `TAX CLASS AT TIME OF SALE` <chr> "1", "1", "1", "1", "1", "1", "…
## \$ `BUILDING CLASS AT TIME OF SALE` <chr> "S1", "A5", "A5", "A9", "A9", "…
## \$ `SALE PRICE` <dbl> 1300000, 849000, 0, 830000, 0, …
## \$ `SALE DATE` <dttm> 2020-04-28, 2020-03-18, 2019-0…
``````

The `glimpse()` function provides a user-friendly way to view the column names and data types for all columns, or variables, in the data frame. With this function, we are also able to view the first few observations in the data frame. This data frame has 20,185 observations, or property sales records. And there are 21 variables, or columns.

#data science tutorials #beginner #r #r tutorial #r tutorials #rstats #tidyverse #tutorial #tutorials

1599097440

## Data Visualization in R with ggplot2: A Beginner Tutorial

A famous general is thought to have said, “A good sketch is better than a long speech.” That advice may have come from the battlefield, but it’s applicable in lots of other areas — including data science. “Sketching” out our data by visualizing it using ggplot2 in R is more impactful than simply describing the trends we find.

This is why we visualize data. We visualize data because it’s easier to learn from something that we can see rather than read. And thankfully for data analysts and data scientists who use R, there’s a tidyverse package called ggplot2 that makes data visualization a snap!

In this blog post, we’ll learn how to take some data and produce a visualization using R. To work through it, it’s best if you already have an understanding of R programming syntax, but you don’t need to be an expert or have any prior experience working with ggplot2

#data science tutorials #beginner #ggplot2 #r #r tutorial #r tutorials #rstats #tutorial #tutorials