var myLocked = Locked(value: Int(5), key: 5)
try myLocked.access(key: 5) { $0 = 10 }
Last active
August 4, 2017 09:55
-
-
Save pauljohanneskraft/e2081e6275be179f622a1e6e966685f3 to your computer and use it in GitHub Desktop.
Locked makes it possible to lock certain variables by a key
This file contains 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
protocol Locked { | |
associatedtype Value | |
associatedtype Key : Equatable | |
mutating func access<T>(key: Key, _ f: (inout Value) throws -> T) throws -> T | |
} | |
struct LockedStruct<Element> : Locked { | |
typealias Key = Int | |
typealias Value = Element | |
private var value : Element | |
private var key : Int | |
mutating func access<T>(key: Key, _ f: (inout Value) throws -> T) throws -> T { | |
guard key == self.key else { throw LockedError.wrongKey } | |
return try f(&value) | |
} | |
} | |
enum LockedError : Error { | |
case wrongKey | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment