[swift-evolution] ternary operator ?: suggestion

Howard Lovatt howard.lovatt at gmail.com
Sun Dec 20 17:31:03 CST 2015


How about removing ?: and adding a simple library:

    struct IfFalse<T> {
        let condition: Bool

        let ifTrue: () -> T

        init(condition: Bool, ifTrue: () -> T) {
            self.condition = condition
            self.ifTrue = ifTrue
        }

        func ifFalse(ifFalse: () -> T) -> T {
            if condition {
                return ifTrue()
            }
            return ifFalse()
        }
    }

    extension Bool {
        func ifTrue<T>(ifTrue: () -> T) -> IfFalse<T> {
            return IfFalse(condition: self, ifTrue: ifTrue)
        }
    }

Used:

    print(true.ifTrue{"True"}.ifFalse{"False"})
    print(false.ifTrue{"True"}.ifFalse{"False"})

Likely to be slower than ?: at the moment, but maybe could be optimised in
the future.

  -- Howard.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20151221/f7068303/attachment.html>


More information about the swift-evolution mailing list