Skip to content

Instantly share code, notes, and snippets.

@john-mueller
john-mueller / WeekdayPicker.swift
Created July 27, 2020 15:55
SwiftUI animation proof-of-concept
//
// WeekdayPicker.swift
//
// Created by John Mueller on 7/27/20.
import SwiftUI
enum Weekday: Int, CaseIterable {
case sunday
case monday
@john-mueller
john-mueller / Character+Codable.swift
Created June 2, 2020 20:17
Codable conformance for Swift's Character
extension Character: Codable {
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(String(self))
}
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
let string = try container.decode(String.self)

Why not just use protocols (never using extensions) or why not just use extensions (never using protocols)?

Protocols serve as a "blueprint" for a struct, class, or enum—they define a set of required properties and methods, as well as any other protocols that must be conformed to. In other words, they are for requiring functionality.

Extensions offer a way to add extra computed properties and methods to an existing struct, class, enum, or to a protocol. In other words, they are for extending functionality.

Because they serve different purposes, they are not either/or concepts. But they can be used together to bring extended functionality to a whole group of structs or classes at once.

Here's a concrete example where I used this recently. I want to be able to take anything that can be encoded as Data, and be able to encrypt it, transmit the encrypted form as Data, then unencrypt it, and decode the unencrypted Data back into an object. Now, I could write an encrypt function for each and every

Why not just use closures (never using functions) or why not just use functions (never using closures)?


Both functions and closures are a way of isolating some functionality, and which may (or may not) take input and may (or may not) return output. In most cases, you will not have to think about “Am I using a function or a closure here?”, as it will all happen behind the scenes. Both functions and closures can be treated as variables and “passed around”. For instance, let’s define a closure and a function:

import Foundation

func function1(string: String, int: Int) -> Data {