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)

Saturday, April 29, 2017

Implementing Control Structures in Swift

In Smalltalk, control structures like "for" or "while" were not part of the language, but built using the language itself. The Smalltalk compiler would special-case these for efficiency, but you could make your own, if you wanted to.

In Swift, you can almost do the same, though the syntax makes it look less like native syntax.

I just wrote this in a Swift playground in Xcode 8.1.

NOTE: just because this is possible, doesn't mean you should do this. Readability and testability matters. This is just exploring the language.

import Foundation

extension Int {
    func through(_ end: Int, `do`: (_ i: Int)->() ) {
        var i = self
        while i <= end {
            `do`(i)
            i += 1
        }
    }
    // originally, I thought of naming this 'to' but that's ambiguous
    // whether the loop executes using the end value or not.
}

print("through loop 12-15")

12.through(15, do: {i in print("\(i)")})

/* prints
 through loop 12-15
 12
 13
 14
 15
*/

print("through loop 1-5")

1.through(5) { index in print("\(index)") }

/* prints:
 through loop 1-5
 1
 2
 3
 4
 5
*/

extension Int {
    func upTo(_ end: Int, `do`: (_ i: Int)->() ) {
        var i = self
        while i < end {
            `do`(i)
            i += 1
        }
    }
}

print("upTo 12-15")

12.upTo(15, do: {i in print("\(i)")})

/* prints
 upTo 12-15
 12
 13
 14
 */

print("upTo 0-5")

0.upTo(5) { index in print("\(index)") }

/* prints
 upTo 0-5
 0
 1
 2
 3
 4
*/

/*

 It's much more readable if you use the built-in syntax:

*/

print("for 12 through 15")

for i in 12...15 {
    print("\(i)")
}

/* prints
 for 12 through 15
 12
 13
 14
 15
*/

print("for 0 up to 5")

for i in 0..<5 { print("\(i)") }

/* prints
 for 0 up to 5
 0
 1
 2
 3
 4
*/

No comments:

Post a Comment