Skip to content

Instantly share code, notes, and snippets.

@alexdrone
Created September 7, 2017 10:59
Show Gist options
  • Save alexdrone/9bee339f85b86f9a80d6b95a8c63773c to your computer and use it in GitHub Desktop.
Save alexdrone/9bee339f85b86f9a80d6b95a8c63773c to your computer and use it in GitHub Desktop.
Object.assign in Swift
import Foundation
// MARK: - Function
/// This function is used to copy the values of all enumerable own properties from one or more
/// source struct to a target struct. It will return the target struct.
public func assign<T>(_ value: T, changes: (inout T) -> Void) -> T {
guard Mirror(reflecting: value).displayStyle == .struct else {
fatalError("'value' must be a struct.")
}
var copy = value
changes(&copy)
return copy
}
// MARK: - Example
struct Aa: DescConvertible {
var text = "foo"
}
struct A: DescConvertible {
var nested = Aa()
var number = 42
}
let a = A()
var b = assign(a) { (argument: inout A) in
argument.nested.text = "bar"
argument.number = 3
}
// MARK: - Debug
public protocol DescConvertible : CustomStringConvertible { }
extension DescConvertible {
/// Returns a representation of the state in the form:
/// Type(prop1: 'value', prop2: 'value'..)
func reflectionDescription(delimiters: String = "") -> String {
let mirror = Mirror(reflecting: self)
var str = "{"
var first = true
for (label, value) in mirror.children {
if let label = label {
if first { first = false } else { str += ", " }
str += "\(label):\(value)"
}
}
str += "}"
return str
}
public var description: String {
return reflectionDescription()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment