Skip to content

Instantly share code, notes, and snippets.

@pauljohanneskraft
Last active July 1, 2016 00:02
Show Gist options
  • Save pauljohanneskraft/89faff5c8e43d939ffc7e1e83142a0a5 to your computer and use it in GitHub Desktop.
Save pauljohanneskraft/89faff5c8e43d939ffc7e1e83142a0a5 to your computer and use it in GitHub Desktop.
Safe - a wrapper struct to safely access data

Safe

let myNumber = 5
var mySafe = Safe(myNumber)
try mySafe.access {
  $0 += 10
  if $0 > 14 { throw SomeError.isGreaterThanFourteen }
}
print( mySafe.value )
// Prints "5"
struct Safe<T> {
private(set) var value : T
mutating func access(_ f: (T) throws -> T) rethrows {
var _value = try f(value)
value = _value
}
mutating func access(_ f: (inout T) throws -> ()) rethrows {
var _value = value
try f(&_value)
value = _value
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment