Optional assignment in Swift
June 10, 2014
In Swift, given a variable x of type Optional<T>, how can guarantee it is not nil? You can force the unwrapping, but this may result in a runtime error. What if we could set x to some default value? We can manually, but this can be cumbersome to do often, so let’s make an operator! This is a good chance to learn about Swift’s optionals, generics, custom operators, and in-out parameters.1
operator infix ~= {}
@assignment func ~=<T>(inout lhs: Optional<T>, rhs: T) {
if lhs == nil {
lhs = rhs
}
}
var x: String? = "nil"
var y: String? = nil
x ~= "Test"
y ~= "Test"
x // "nil"
y // "Test" I’d prefer ?= but ? is not allowed in custom operators.
I apologize for the poor syntax highlighting!↩
kms