Created
September 7, 2017 10:59
-
-
Save alexdrone/9bee339f85b86f9a80d6b95a8c63773c to your computer and use it in GitHub Desktop.
Object.assign in Swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(©) | |
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