Is there an equivalent to optional chaining with arithmetic operators?

I have two optional numbers that I add. Now it looks like this:

if let a = optionalA {
    if let b = optionalB {
        return a + b
    }
}
return nil

      

There is a more convenient additional chaining syntax for methods, such as syntax optionalA.?method

. Is there an equivalent for arithmetic operators returning nil

if each side was nil

?

+3


source to share


3 answers


You can create a statement +?

that does it something 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 is another, built-in way to do this.

+1


source


I don't think it's built in there. 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

      

+1


source


Here's a custom user experience updated for Swift 3:

infix operator +?
func +?(a: Int?, b: Int?) -> Int? {
    if let aa = a, let bb = b {
        return aa + bb
    }
    return nil
}

      

0


source







All Articles