zneak
zneak

Reputation: 138211

Is there an equivalent to optional chaining with arithmetic operators?

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

Answers (3)

Rogare
Rogare

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

Kirsteins
Kirsteins

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

zneak
zneak

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

Related Questions