Skip to content

Instantly share code, notes, and snippets.

@zoejessica
Forked from nicklockwood/Withable.swift
Created April 24, 2020 23:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zoejessica/2bd3bc0c9e8fd04065474c77e27da447 to your computer and use it in GitHub Desktop.
Save zoejessica/2bd3bc0c9e8fd04065474c77e27da447 to your computer and use it in GitHub Desktop.
Withable.swift
/// Withable is a simple protocol to make constructing
/// and modifying objects with multiple properties
/// more pleasant (functional, chainable, point-free)
public protocol Withable {
init()
}
public extension Withable {
/// Construct a new instance, setting an arbitrary subset of properties
init(with config: (inout Self) -> Void) {
self.init()
config(&self)
}
/// Create a copy, overriding an arbitrary subset of properties
func with(_ config: (inout Self) -> Void) -> Self {
var copy = self
config(&copy)
return copy
}
}
//---------------------------------------------------
// Example struct
struct Foo: Withable {
var bar: Int = 0
var baz: Bool = false
}
// Construct a foo, setting an arbitrary subset of properties
let foo = Foo { $0.bar = 5 }
// Make a copy of foo, overriding an arbitrary subset of properties
let foo2 = foo.with { $0.bar = 7; $0.baz = true }
// Test
print("\(foo.bar), \(foo2.bar)") // 5, 7
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment