Skip to content

Instantly share code, notes, and snippets.

@alvarhansen
Forked from nicklockwood/Withable.swift
Created February 5, 2019 08:06
Show Gist options
  • Save alvarhansen/39c82ac7ee5117c4c1926f4acd1289cf to your computer and use it in GitHub Desktop.
Save alvarhansen/39c82ac7ee5117c4c1926f4acd1289cf 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