Reputation: 138211
I have two optional numbers that I add. Right now it looks like this:
if let a = optionalA {
if let b = optionalB {
return a + b
}
}
return nil
For methods, there's the more convenient optional chaining syntax, like optionalA.?method
syntax. Is there an equivalent for arithmetic operators that would return nil
if either side was nil
?
Upvotes: 4
Views: 646
Reputation: 3274
Here's the custom operator approach updated for Swift 3:
infix operator +?
func +?(a: Int?, b: Int?) -> Int? {
if let aa = a, let bb = b {
return aa + bb
}
return nil
}
Upvotes: 0
Reputation: 27345
I dont think there is built in way. But you can make your own operator function:
func +(lhs: Int?, rhs: Int?) -> Int? {
if let a = lhs {
if let b = rhs {
return a + b
}
}
return nil
}
var a: Int? = 1
var b: Int? = 2
var c = a + b
Upvotes: 1
Reputation: 138211
It's possible to create an operator +?
that does just this like this:
infix func +?(a: Int?, b: Int?) -> Int? {
if aa = a {
if bb = b {
return aa + bb
}
}
return nil
}
but I'm wondering if there's another, built-in way to do that.
Upvotes: 1