Optional chaining lets us make decisions on the existence of objects:
var text : String?
let len = text?.lengthOfBytes(using: .utf8) ?? 0
Which will always set len
to an integer.
Is something similar possible for non-optional function arguments? Consider the following example, which already is less elegant with the ternary operator.
func length(text: String) -> Int {
return text.lengthOfBytes(using: .utf8)
}
var text : String?
let len = (text != nil) ? length(text!) : 0
If we keep chaining, it easily gets a mess (and this is what I am actually looking at):
let y = (arg!= nil) ? (foo?.bar(arg!) ?? 0) : 0 // how to improve on this?
Besides, it also starts to get redundant, defining the default value twice.
Is there any more concise solution to the last line?