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 "==".


Tuesday, September 19, 2017

What Every Programmers Needs to Know About Swift



I have a book in progress at LeanPub titled What Every Programmer Needs to Know About Swift.

I've set the minimum price to $0.00 for a while, so buying the book now is at no risk for you. (Plus, LeanPub has a money-back guarantee. See also their Terms of Service.)

This book is intended for people who already know a programming language and are getting started using Swift. Or, you may already know Swift, but have questions. Or, like me, you keep forgetting the syntax and you’re tired of searching the web and having to carefully read the pages you find to figure out which version of the Swift language some example code was written in. Plus, the page you find on the web might be wrong or long-winded.

My book is written for Swift 4, and every line of code has been tested in a Swift playground in Xcode. You should be able to copy and paste my code confidently.

It's in a question-and-answer format inspired by C++ Faqs by Cline and Lomow. (There are more recent C++ Faqs books on Amazon, which, if they are as good as the original edition, you should read if you’re programming in C++.

I'm also going to publish snippets from the book on my blog.

If you buy the book, please join and participate on the mailing list! (See the Introduction in the book.)