let myNumber = 5
var mySafe = Safe(myNumber)
try mySafe.access {
$0 += 10
if $0 > 14 { throw SomeError.isGreaterThanFourteen }
}
print( mySafe.value )
// Prints "5"
Last active
July 1, 2016 00:02
-
-
Save pauljohanneskraft/89faff5c8e43d939ffc7e1e83142a0a5 to your computer and use it in GitHub Desktop.
Safe - a wrapper struct to safely access data
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
| 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