AssertingNilCoalescing Operator !!
I believe that Swift needs one more operator to deal with optionals, in this post I present my concept to make dealing with them better and safer. It isn't a beginners introduction to optionals or Swift. There are plenty of good ones out there already.
infix operator !! { associativity right precedence 110 }
public func !!<A>(lhs:A?, rhs:@autoclosure()->A)->A {
assert(lhs != nil)
return lhs ?? rhs()
}
How this code works will be explained near the end of this post so don't feel you need to understand it now. It adds an additional operator !!
to a Swift project for dealing with optionals. It is designed to retain the benefits of strong typing proving the validity of some aspects of the code while documenting the expectation that the left hand argument will not be nil and exposing (in debug builds only) if that belief about the code is wrong.
Unlike other operators it behaves differently in a debug build than a release build. In release builds it is exactly the same as the built in ??
nil coalescing operator return the argument on the left unless it is nil in which case the right hand argument will be returned.
Read more »