I would like to have a built in =? operator which only assigns if the rhs is non-nil. If the rhs is nil, then it would do nothing.
I can make it myself (and have for my own projects), but I make a lot of frameworks and custom controls, and I don't want to unexpectedly make custom operators in other people's code base.
I use this fairly often, and one of the main areas where it comes in handy is in NSCoding.
With the =? operator
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
color =? aDecoder.decodeObjectForKey("color") as? UIColor
borderWidth =? aDecoder.decodeObjectForKey("borderWidth") as? CGFloat
borderColor =? aDecoder.decodeObjectForKey("borderColor") as? UIColor
commonSetup()
}
As you can see, if a coded object has been stored (as the expected type), then it updates the default value. If it has not been stored, then it leaves it at the current/default value.
Without the =? operator, I have to recreate the defaults (which can get out-of-sync)
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
color = aDecoder.decodeObjectForKey("color") as? UIColor ?? UIColor.blackColor()
borderWidth = aDecoder.decodeObjectForKey("borderWidth") as? CGFloat ?? 1.0
borderColor = aDecoder.decodeObjectForKey("borderColor") as? UIColor ?? UIColor.blackColor()
commonSetup()
}