Schwern
Schwern

Reputation: 165200

What is the equivalent to `thing = this() || that` in Swift 3?

In most languages I can write something like this:

this = this() || that()

If this() returns something false, like integer 0, that() will be evaluated. Pretty common idiom.

Swift 3 doesn't automatically cast Int to Bool so that idiom doesn't work. What is a succinct way to do it in Swift 3?

Upvotes: 0

Views: 179

Answers (2)

dfrib
dfrib

Reputation: 73196

The nil coalescing operator as covered by @OOPer:s answer is the fit for purpose idiom here, but as a side-note, you could implement functionality as the one your describe by overloading the || operator, e.g. for types that conform to some type constraint. E.g. using Integer as type constraint:

extension Bool {
    init<T : Integer>(_ value: T) {
        self.init(value != 0)
    }
}

func ||<T: Integer>(lhs: T, rhs: @autoclosure () -> T) -> T {
    return Bool(lhs) ? lhs : rhs()
}

var thisNum = 0
let thatNum = 12
thisNum = thisNum || thatNum
print(thisNum) // 12

Upvotes: 1

OOPer
OOPer

Reputation: 47896

There's no exact equivalent in Swift, as:

  • No other types than Bool cannot be converted to Bool

  • You cannot write a function returning Bool or Int

(In most languages is a little bit exaggerated, you cannot write such thing in Java, C# or many other strongly-typed languages.)

The most similar thing in Swift is nil-coalescing operator -- ??.

Assume this() returns Int? (aka Optional<Int>), and that() returns Int (non-Optional):

func this() -> Int? {
    //...
    if someCondition() {
        return intValue
    } else {
        return nil
    }
}

func that() -> Int {
    //...
    return anotherIntValue
}

And use nil-coalescing operator like this:

let result = this() ?? that()

In this assignment, if this() returns non-nil value, then that() is not evaluated, and that non-nil value is assigned to result. When this() returns nil, that() is evaluated and the value is assigned to result.

Upvotes: 2

Related Questions