Skip to content

Instantly share code, notes, and snippets.

@pauljohanneskraft
Last active August 4, 2017 09:55
Show Gist options
  • Save pauljohanneskraft/e2081e6275be179f622a1e6e966685f3 to your computer and use it in GitHub Desktop.
Save pauljohanneskraft/e2081e6275be179f622a1e6e966685f3 to your computer and use it in GitHub Desktop.
Locked makes it possible to lock certain variables by a key

Locked

var myLocked = Locked(value: Int(5), key: 5)
try myLocked.access(key: 5) { $0 = 10 }
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