C. Keith Ray

C. Keith Ray writes about and develops software in multiple platforms and languages, including iOS® and Macintosh®.
Keith's Résumé (pdf)

Wednesday, September 20, 2017

Is True Greater Than False in Swift 4?

This is a sample from my book in progress at LeanPub: What Every Programmer Needs to Know About Swift.

Is true > false?

Relational operators ("<", ">", "<=", ">=") are not defined for Bool values. So "true > false" is a syntax error.
However, if you want those operators to work with Bool values (so you can sort "false" before "true", for example), you canmake Boolean conform to the "Comparable" protocol. I'll illustrate:
extension Bool : Comparable {
    // "Is the left-hand-side value 
    // less than the right-hand-side value?"
    public static func <(_ lhs: Bool, _ rhs: Bool) 
            -> Bool {
        switch (lhs, rhs) {
            case (false, true):
                return true
            default: 
                return false
        }
    }
}

assert( (true  >  false) == true )
assert( (true  >= false) == true )
assert( (true  <  false) == false )
assert( (true  <= false) == false )
assert( (false >  true)  == false )
assert( (false >= true)  == false )
assert( (false <  true)  == true )
assert( (false <= true)  == true )
The Comparable protocol requires two operators be implemented: "<" and "==". It defines the other relational operators in terms of those two. I only need to implement "<", since Bool already implements "==".


No comments:

Post a Comment