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
*/

Saturday, April 15, 2017

Template Design Pattern in Swift

In the Template Design pattern, you write an abstract class where an algorithm is implemented, but at least one part of the algorithm is not implemented -- it calls an abstract/unimplemented method for some part of the algorithm. The subclass inherits from the abstract class, implementing the abstract method(s) but not changing the overall algorithm. 

I will show two ways to implement this design pattern.

First, using classes:

import Foundation

class TemplateClass { // "Abstract" class
    func doit() {
        before()
        during()
        after()
    }
    func before() {
        print("before")
    }
    
    func during() { // in C++ should be "pure virtual".
        fatalError("subclass must override")
    } // in Java, should be "abstract"
    
    func after() {
        print("after")
    }
}

class TemplateClassExample: TemplateClass {
    
    override func during() {
        print("during")
    }
}

var tx = TemplateClassExample()

tx.doit() // prints "before", "during", "after"

As you can see, Swift doesn't allow us to declare a method "abstract". It's similar to Objective-C and Smalltalk in this way. We can put in an assertion or throw an exception, but we don't have the compiler forcing us to override/implement the abstract method.

Second, using Protocols:

protocol TemplateProtocol {
    func during()
}

extension TemplateProtocol {
    func doit() {
        before()
        during()
        after()
    }
    func before() {
        print("before")
    }
    func after() {
        print("after")
    }
}

class TemplateProtocolExample: TemplateProtocol {

    internal func during() {
        print("during")
    }
}

var tp = TemplateProtocolExample()

tp.doit() // prints "before", "during", "after"

Here the protocol forces us to implement the abstract method, but we can't put the algorithm's concrete methods in the protocol declaration, they have to go in the protocol extension. This seems to be a rather arbitrary restriction, but it's probably reflecting the way Swift evolved. I don't think the earliest versions of Swift allowed extending protocols with extensions containing concrete methods, though obviously Swift 3.x does allow this.