Created
October 31, 2019 11:28
-
-
Save junpluse/4858d5db97dff58683caf1d7267b6554 to your computer and use it in GitHub Desktop.
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 | |
/// A type that privides mutation interface for a wrapped value. | |
public struct Mutation<Value> { | |
/// The wrapped value. | |
public var value: Value | |
/// Creates an instance that wraps the given value. | |
/// | |
/// - Parameter value: The value to store. | |
public init(_ value: Value) { | |
self.value = value | |
} | |
/// Returns a mutated copy of the original wrapped value using the given | |
/// closure. | |
/// | |
/// - Parameter body: A closure that takes the wrapped value of the instance. | |
/// - Returns: The mutated copy of the wrapped value. | |
public func mutated(_ body: (inout Value) throws -> Void) rethrows -> Value { | |
var v = self.value | |
try body(&v) | |
return v | |
} | |
/// Invokes the given closure with a pointer for the wrapped value. | |
/// | |
/// - Parameter body: A closure that takes the wrapped value of the instance. | |
public mutating func mutate(_ body: (inout Value) throws -> Void) rethrows { | |
try body(&self.value) | |
} | |
} | |
extension Mutation where Value: NSObject { | |
/// Creates an instance that stores a value initialized using `init()`. | |
public init() { | |
self.value = Value() | |
} | |
/// Returns a mutated value which initialized using `init()`. | |
/// | |
/// - Parameter body: A closure that takes a value initialized using `init()`. | |
/// - Returns: The mutated value. | |
public static func mutated(_ body: (inout Value) throws -> Void) rethrows -> Value { | |
return try Mutation().mutated(body) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment