June 30, 2014

Swift, NSOperationQueues, Closures, and Threading

Posted in iPhone development, mac development tagged , , , at 3:49 pm by tetontech

In a previous posting I showed how to inherit from NSOperation to do work in background processes using NSOperationQueues. In another, I showed how to use Grand Central Dispatch, GCD, to do threading. In this post I’ll give a simple example of using NSOperationQueues without NSOperations.

For this example I created a single view application, added a label to the view using Interface Builder, and added an IBOutlet for the label called ‘theLabel’ to the ViewController for the view. theLabel can only be updated by the main application thread. This means that inside the code running in the background there must be a a call that runs code in the main application thread.

To take advantage of Swift’s closures, this example uses the NSOperationQueue method called ‘addOperationWithBlock.’ Blocks are the Objective-C equivalent to Swift’s closures. Line’s 2 and 4 show the addOperationWithBlock method being used.

Line 2 adds a closure to a background queue that was created on line 1. The code in the closure will be run on a background thread. Line 4 adds a closure to the main thread’s queue for execution. Line 4 does this by taking advantage of the NSOperationQueue class method ‘mainQueue.’ mainQueue returns the queue for the application’s main thread. This means that anything in the closure defined on lines 4 – 6 will execute in the application’s main thread.

1       var backgroundQueue = NSOperationQueue()
2       backgroundQueue.addOperationWithBlock(){
3           println("hello from background")
4           NSOperationQueue.mainQueue().addOperationWithBlock(){
5               self.theLabel.text = "updated from main thread"
6           }
7       }

By creating a closure within a closure you can execute code in a background thread and after it has completed you can execute code in the main or ‘UI’ thread. You can also use if statements to update the UI in different ways depending on what happens in the background thread.


June 25, 2014

Swift, Objects, Arrays, and Simulation

Posted in iPhone development, mac development, simulation tagged , , , , at 9:24 pm by tetontech

One of the tasks I give myself when learning a new language is to write a traditionally designed discrete event simulation engine. This is due to my background in creating and supporting simulation software for the semi-conductor industry. Another reason is that it gives me a frame of reference I’m comfortable with and allows me to focus on how the different parts of the new language interact with each other.

To highlight certain Swift concepts and how they can interact I’ll go over some of my simulation engine’s code. The entire code set is available on gitHub in the SimSwift-Traditional repository. It includes 3 files – Engine.swift, Event.swift, and ViewController.swift.

The simplest file is Event.swift so let’s start there. It describes the Event class, its attributes, and its behaviors.

The Event class has two constant properties, an integer that represents the time that the event should occur, and a closure or function that is the action to be taken at that time. The trigger time is used by the engine to sort and group events that need to happen. I chose Int as the datatype to allow maximal flexibility for the engine. Time in the engine could be milliseconds since the unix epoch time. It could also be zero based and have each event trigger at some number of seconds, milliseconds, hours, days, or some other offset from the beginning of the simulation.

 24 import Foundation
 26 class Event{
 27     let triggerTime:Int
 28     let action:()->()
 30     init(aTriggerTime:Int, anAction:()->()){
 31         triggerTime = aTriggerTime
 32         action = anAction
 33     }
 34 }

The Event class includes an init method. Swift classes need to have init methods to set properties. If you don’t declare an init method Swift will not generate a default at compile time in most cases. In the init method  the parameters are assigned to their matching properties. You also see that the parameters are named parameters. This means that when init is called the parameter names are used to delimit the parameters. I’ll show you how to use the delimiters when we look at some of the code in the ViewController.swift file.

The simulation engine class, TraditionalEngine, has three variable properties. The time property represents the ‘current’ time of the simulation, futures are events that need to happen at some future time, and presents are events that have trigger times that match the ‘current’ time of the simulation.

class TraditionalEngine{
    var time:Int
    var futures:Array<Event>
    var presents:Array<Event>
        time = startTime
        futures = Array<Event>()
        presents = Array<Event>()

The init method for the TraditionalEngine class has one named parameter, startTime. startTime represents the initial time of the simulation. The futures and presents arrays are set to empty arrays so events can be added later.

I’ve given the engine an addEvent method. It has one named parameter, an. One purpose of the addEvent method is to determine if the event should be added to the presents or the futures array. Which it is added to depends on if the event’s triggerTime is after the current time of the simulation.

    func addEvent(an:Event){
        an.triggerTime > time ? insertEvent(an, isFuture: true)
                                     : insertEvent(an, isFuture: false)

I chose to use Swift’s ternary operator ( ? : ) for reasons of succinctness. If the event’s trigger time is greater than the simulation’s current time the event is inserted into, not appended to, the futures array, otherwise it is inserted into the presents array. In either case a binary search insertion is performed.

Why do insertion in the presents list? From industry experience I know that events users setup to start simulations sometimes happened in the past. By using an insertion based approach, events in the past will be triggered before the current ones. Let’s look at the code that does the insertion later. First we’ll take a look at the simulation’s run loop found in the engine’s go method.

While there are events waiting in the future or events for the current time the simulation loop continues. In the loop any present events are triggered and then the next group of events are found, executed, and the loop continues. This is the heart of any traditionally designed simulation engine.

    func go(){
        while(self.futures.count > 0 || self.presents.count > 0){
    func doAnyPresents(){
        while presents.count > 0 {
    func doNextGroup(){
        if futures.count > 0 {
            let nextPresent = futures.removeAtIndex(0)
            self.time = nextPresent.triggerTime
            while futures.count > 0 
                  && futures[0].triggerTime == self.time{

The doNextGroup method pops the first event off the futures array and sets the simulation’s current time to the popped event’s triggerTime. This is what causes time to move forward in the simulation. Thankfully, it also means we don’t need to simulate the time between events when nothing is happening. The doNextGroup method executes all events that match the current time.

Why then does the simulation loop always call doAnyPresents before calling doNextGroup? In discrete event simulations it is common for events to create new events that have the same trigger time as the current time. Rather than make the programmer using the simulation’s API write if statements all over in their code they can use the addEvent method and not have to worry about which Array to add it to. If the event has a trigger time that matches the simulation’s current time it will end up in the currents Array and be executed before the simulation moves on to the next group of events.

Rather than put a code listing for the entire insertEvent method please go view it or download the source from the gitHub repository. It is a standard binary search for an insertion point. To minimize computation, a check is done before doing the binary search. If the trigger time of the event being added is less than the first event’s trigger time the event is prepended. If it is greater than the last event’s trigger time the event is appended. If it is somewhere in-between the binary search process is executed. See the source from gitHub to for the full implementation of the binary insertion algorithm.

One part of the implementation is interesting. To avoid the array copy problem explained in a previous post, the engine’s list properties are modified directly rather than trough a facade-like approach.

isFuture ? futures.insert(an, atIndex: midIndex) 
         : presents.insert(an, atIndex: midIndex)

This line of code is longer and less expressive than I would like it to be but it does avoid the copy problem.

There is some sample code in the ViewController class that shows the engine’s API being used. In it a TraditionalEngine is instantiated and stored as a parameter of the ViewController. 0 is used as the start time of the simulation so all event triggerTimes are considered to be time offsets. In viewDidLoad 50 random integers from 0 – 100 are created and if any of them are a multiple of 15 they are made negative. This will exercise the code handling the situation where the simulation has events to process from before the beginning of the simulation.

class ViewController: UIViewController {
    let theEngine = TraditionalEngine(startTime:0)
    override func viewDidLoad() {
        for index in 0..50{
            var randNum = Int(arc4random() % 100)
            if randNum % 15 == 0 {
                randNum = -randNum
            let capturedNum = Int(arc4random() % 50)
            theEngine.addEvent(Event(aTriggerTime: randNum, anAction: {
                println("triggered at: \(randNum) with 
                                   captured: \(capturedNum)")

I’ve used a closure as the action for the events. I chose a closure to show how a constant or variable could be captured and used later when the event’s action is triggered.

All in all, Swift worked quite well for creating a traditionally designed simulation engine.

Swift, facades, and Objects with Collection Type Properties

Posted in iPhone development, mac development tagged , , , , at 7:26 pm by tetontech

Facade functions are very common in software. One of reason to use them is to put common code in a single function but have it behave differently without needing to pass one or more extra parameter indicating which behavior to execute. In Swift this can be problematic if we forget that Arrays, if passed to functions or methods, are copied if something is added to or removed from the passed Array.

Here is an example that separates negative numbers from zero and positive numbers. I have called the class DoesNotWork1 because it doesn’t work in Swift. The negativeInts and positiveInts arrays will always be empty. This is because the Arrays were passed to the _storeInt method.

import Foundation

class DoesNotWork1{
    var negativeInts:Array<Int> = Array<Int>()
    var positiveInts:Array<Int> = Array<Int>()
    func storeInt(an:Int){
        if an < 0{
            _storeInt(an, list:negativeInts)
            _storeInt(an, list:positiveInts)
    func _storeInt(an:Int, var list:Array){


OK … lets try another approach. It is less common that the previous example but is also frequently used. I have named this variation DoesNotWork2. This one doesn’t work for the same underlying reason that DoesNotWork1 fails. The Arrays are getting copied. Why? Because operators in Swift are functions. The arrays passed to the ternary operator ( ? : ) will be copied as soon as we try to modify their length.

import Foundation

class DoesNotWork2{
    var negativeInts:Array<Int> = Array<Int>()
    var positiveInts:Array<Int> = Array<Int>()
    func storeInt(an:Int){
        _storeInt(an, isNegative:an < 0)
    func _storeInt(an:Int, isNegative:Bool){
        var list = isNegative ? negativeInts : positiveInts

What then could a programmer do to create a facade that modifies specific arrays depending on the situation? I’ve called this example DoesWork. The difference is what happens in the ternary ( ? : ) operator. Instead of selecting and returning one of the class’s arrays it modifies them directly.

import Foundation

class DoesWork{
    var negativeInts:Array<Int> = Array<Int>()
    var positiveInts:Array<Int> = Array<Int>()
    func storeInt(an:Int){
        _storeInt(an, isNegative:an < 0)
    func _storeInt(an:Int, isNegative:Bool){
        isNegative ? negativeInts.append(an) : positiveInts.append(an)


June 17, 2014

Swift, Pipelining, Function Arrays, and Operator Overloading

Posted in Uncategorized tagged , , , , , , , at 9:46 pm by tetontech

In a previous post I showed how to create a pipeline operator, |>, that allows chaining of functions, closures, and mixtures of functions and closures. This posting will overload the pipeline operator so it can be used in a related but different situation.

In functional programming there are known good patterns. Two of these are map and reduce. Reduce applies a single function to an array of values and returns a single value. Summing the values in an array of Ints would be a good example.

Map is similar. It also applies a single function to an array of values. It returns a new array containing one value for each value in the original array but the new array values have been modified by applying the function. An example would be to map a double process to the array [1,2,3] generating and returning the new array [2,4,6].

There is yet another pattern that is common in programming and I use it a lot . It is related to map and reduce. In this situation a single piece of data, be it a Dictionary, Array, Int, String, or any other type, is passed to a series of functions. I haven’t seen a specific name for this type of behavior so I refer to it as spindle (a play on words – fold, spindle, or mutilate).

An example situation that fits the spindle pattern is the validation and application of data received from a source such as a file, a server, the user, etc. In this example I’ll be doing something that is so common in programming that it can seem trivial; validating a user name and password, authenticating the user, and displaying the user interface appropriate for the user. To do this let’s pretend that the data to be validated has come to us as JSON and been converted into a Swift Dictionary having the structure [“uName”:,”pWord”:,”userRole”:].

A few functions to apply in our example would be helpful. These consist of different portions of the validation, authentication, display process. In each function a Tuple is returned consisting of a Dictionary<String,AnyObject> and a String? (String optional) (see my previous post for an explanation of using AnyObject with Dictionaries). The String? is used by the overloaded pipeline operator for error detection and early process termination. The example functions are:

func checkUName(data:Dictionary<String, AnyObject>) 
              -> (Dictionary<String,AnyObject>, String?){  
    if let userNameOptional = data["userName"]? as? String{
            if countElements(userNameOptional.stringByTrimmingCharactersInSet(
                   NSCharacterSet.whitespaceAndNewlineCharacterSet())) > 0{
                return (data, nil)
    return (data, "missing user name")
func checkPWord(data:Dictionary<String,AnyObject>) 
            -> (Dictionary<String,AnyObject>, String?){
    if let passWordOptional = data["passWord"]? as? String{
        if countElements(passWordOptional.stringByTrimmingCharactersInSet(
                  NSCharacterSet.whitespaceAndNewlineCharacterSet())) > 0{
            return (data, nil)
    return (data, "missing password")
//var data declares the data Dictionary to be variable rather than fixed.
//This is still functional since data is a copy of 
//the original data Dictionary.  
func isUser(var data:Dictionary<String,AnyObject>) 
             -> (Dictionary<String,AnyObject>, String?){
    // place authentication code here.
    if authentication passes 
          return (data, nil)
          data["isLoggedIn"] = true
    return (data, "invalid user name or password")
func showRoleDisplay(data:Dictionary<String,AnyObject>) 
              -> (Dictionary<String,AnyObject>, String?){
    // based on data["userRole"] show a view that matches the users role.
    return (data, nil)

For this example we create an Array called login that represents the entire process by listing the functions in the order we want them executed.

var login = [checkUName, checkPWord, isUser, showRoleDisplay];

A Dictionary for use in our example is also created.

var user:Dictionary<String,AnyObject> = ["userName":"sue", 
                        "passWord":"gr4583rt!", "userRole":14]

Using the pipeline operator we will see below, the code to apply login to the user Dictionary is

let (aResult, errorMessage) = login|>user

This line of code reads “Let a tuple be assigned the result of attempting to login a user.” You could also think of it as “Apply login to user and assign the result to a Tuple.” Either way you view the line of code, it seems to read well due to the operator.

So what does the code for the overloaded pipeline operator, |>, look like?

Since we declared the operator in a previous post and are using the same project we do not need to redeclare the operator. The code to overload it is

1 func |> <T>(left: Array<(T) -> (T, String?)>, var right: T ) -> (T, String?){
2    for function in left{
3        let (partialResult,message) = function(right)
4        if message != nil{
5            return (partialResult, message)
6        }
7        right = partialResult
8    }
9    return (right, nil)

Operators are functions so the first line includes the func keyword, the name of the operator, two parameters, and a return of a tuple that includes a String optional. The first parameter, left, is an Array of functions that accept any type T and return a Tuple consisting of that type T and a String optional. The second operator, right, is a variable of the same type T.

Line 2 of the operator iterates over each of the functions in the left parameter. Each function is then called on line 3 and its returned result is checked on line 4. If an error message has been received it, along with the object of type T, partialResult, is returned to break the loop and early terminate the execution of the array of functions.

Line 7 updates the result that will be passed to any subsequent functions called or returned as part of line 9.

This operator can also be used with closures since functions are named closures in Swift.

Swift Arrays and Dictionaries with Various Types of Values using AnyObject

Posted in iPhone development, mac development tagged , , , , , at 7:25 pm by tetontech

Apple’s Swift documentation declares that Arrays and Dictionaries can only hold one type of value per collection. This is true but Apple’s examples are a little misleading. The code

var stArr:Array<String> = [“bob”,“sue”]

does create an Array named stArr that holds only strings. If you tried to add a number to stArr the code would fail to compile. The code

var anotherStrArr = [“sally”,“joe”]

would also create an Array that can only hold strings. An Array that can only hold Ints would be created from the code

var intArr = [4,56,7,12]

Whether the type is declared, as in the first example, or is the result of interpolation, as in the second and third example, only one type is storable in each of these Arrays.

What is not explained in Apple’s documentation is the use of AnyObject. The code

var interestingArray:Array<AnyObject> = [“sally”, “jones”, 45]

is not only legal, but it compiles and runs. Why?

Because all of the values in the array of of type AnyObject. An Array of AnyObjects can also be created by the interpolator.

var interpolatedInterestingArray = [“sally”“jones”, 45]

interestingArray and interpolatedInterestingArray will be identical in type and values. Understanding this isn’t particularly helpful if we restrict ourselves to Arrays. It can be very helpful when Dictionaries are being used. The code

var aPersonDictionary:<String,AnyObject> = [“firstName”:“sally”, “lastName”:“jones”, “age”:45]

is completely legal, creates a Swift Dictionary, and works well because all key-value pairs are of the same type: <String,AnyObject>. WARNING! The code

var interpolatedPersonDictionary = [“firstName”:“sally”“lastName”:“jones”“age”:45]

doesn’t yield the same result. Instead, the interpolator will assign a NSDictionary to the variable interpolatedPersonDictionary rather than a Swift Dictionary. This is important to know if you have a function that expects a Swift Dictionary. You can not directly pass an NSDictionary as a Swift Dictionary. They are not the same type.

My next post contains an operator and functions that need a Swift Dictionary using AnyObject rather than an interpolated NSDictionary.

June 13, 2014

Swift, WKWebView, and Calling from Swift to Javascript

Posted in Uncategorized tagged , , , , at 7:34 pm by tetontech

Update: If you are interested in this topic you may find this new post helpful. It describes and updated version of the example code you see here and standardizes it for both Swift and Android.

In a previous post, I showed how to embed Apple’s new WKWebView using Swift to create a ‘full view’, hybrid JavaScript application. An ability that QC Hybrid and PhoneGap, both early hybrid development platforms, had was to allow calls to be made from Javascript down to the native language of the device. In the case of iOS that was, and can still be, Objective-C but now can also be done in Swift. The new WKWebView has new functionality available in both languages that requires much less overhead to accomplish this interoperability than the old iOS UIWebView and Android WebView. The WKWebView currently does have an important limitation I’ll discuss in a moment.

There are two parts needed to achieve iOS’s new interoperability; a ‘listener’ of type WKScriptMessageHandler on the Swift side and a new object that has a postMessage() method on the Javascript side. When the Javascript postMessage() method is passed an array, associative array, object, or other Javascript type, the postMessage() method will JSON what it was passed. It then pushes this JSON string as a message to a queue on the Swift side of the application. At this point the JSON is parsed and the message becomes the matching Swift types, Array, Dictionary, String, Int, Double, etc. Custom Javascript objects become Dictionaries. Now your code in the WKScriptMessageHandler’s didRecieveMessage() method has Swift objects without needing to use JSON libraries in either the Javascript or Swift portions of your code. This is great. Unfortunately, at the time of this posting, there is no matching functionality in the beta release to easily push Swift objects back up to Javascript. Hopefully this will come soon. If not, there will need to be some ‘hack-like’ work-arounds similar to what QC Hybrid and PhoneGap had to do. This would be unfortunate.

The source code for this posting’s example is a modification of the previous post’s source. Rather than repeat the discussion of those portions of the example I’d suggest you review the previous post about how to do the embedding. The example below is the contents of a ViewController.swift file. It includes the changes needed to setup JS -> Swift interoperability (JS->Objective-C would use the same classes and methods) for an iOS single view application. The changes can be seen in lines 4, 14-18, and 29 – 31.

Line 4 declares the ViewController class as conforming to the WKScriptMessageHandler protocol. Notice that unlike Objective-C, Swift protocol declarations look just like object inheritance calls (in this case ViewController inherits from UIViewController). Swift only allows single inheritance, like Java. When doing both inheritance and protocol declarations the inheritance declaration must come first. If no inheritance is being done then a protocol declaration can be the first item after the : operator.

(Note: This code example has been updated for Swift 2.0 on my gitHub repository.)

1 import UIKit
2 import WebKit
4 class ViewController: UIViewController, WKScriptMessageHandler {
6    override func viewDidLoad() {
7        super.viewDidLoad()
9        //prepare
10        var path = NSBundle.mainBundle().pathForResource("index", 
                                        ofType: ".html")
11        var url = NSURL(fileURLWithPath:path)
12        var request = NSURLRequest(URL:url)
14        //changes from last post
15        var theConfiguration = WKWebViewConfiguration()
16        theConfiguration.userContentController.addScriptMessageHandler(self, 
                                        name: "interOp")
17        var theWebView = WKWebView(frame:self.view.frame, 
                                        configuration: theConfiguration)
18        //end of changes
20        theWebView.loadRequest(request)
21        self.view.addSubview(theWebView)
22    }
24    override func didReceiveMemoryWarning() {
25        super.didReceiveMemoryWarning()
26        // Dispose of any resources that can be recreated.
27    }
29    func userContentController(userContentController: WKUserContentController!, didReceiveScriptMessage message: WKScriptMessage!){
30        println("got message: \(message.body)")
31    }
33 }

Line 15 introduces a new class, WKWebViewConfiguration. This class manages various types of configurations for any and all WKWebViews used in your applications. One of the WKWebViewConfiguration’s properties is a content controller named userContentController. This is the object we need to access in order to setup the ViewController class as the ‘listener’ for messages from Javascript.

Line 16 shows how to assign the ViewController to be the Javascript message handler for any messages generated as part of the named message queue ‘interOp’. You can select any name you want instead of interOp. It just sounded good to me.

Line 17 shows how to initialize the WKWebView with both a frame and the WKWebViewConfiguration instance. This tells the WKWebView to create an opportunity to use the Javascript postMessage() method.

We’re almost done. The only other change needed is to create the ‘listener’ method, userContentController.didRecieveScriptMessage(). One of the parameters to this method will be the WKScriptMessage generated as part of the interoperation between your JavaScript and Swift. The message has a property named body that is the Swift version of the JSON data passed from JavaScript. Line 30 shows this example printing the Swift objects that the example sends from the Javascript side.

I created a simple Javascript function in the project’s main.js file that you can see below. Notice the new window.webkit.messageHandlers object. It has an attribute ‘interOp’ that matches the name we used on line 16 of the Swift code. The JavaScript interOp object is the ViewController since it conforms to the WKScriptMessageHandler protocol and was assigned on line 16 with the interOp name.

function sendMessage(){
    var aMessage = {'command':'hello', data:[5,6,7,8,9]}

That’s it. Now we can send any object, array, or primitive as a message to Swift. Hopefully Google will not re-invent the wheel when they add this same type of interoperability to Android. They should make their Javascript side look exactly this same way. There is some advantage to copying.

For an example of how to call from JavaScript to Swift and then back to JavaScript see this other post.

June 12, 2014

Swift Hybrid Development

Posted in iPhone development, mac development tagged , , , , , , , , , , , , at 3:02 pm by tetontech

From 2007 until 2012 when my doctoral degree got in the way I created and then supported a hybrid development environment call QC Hybrid. It was designed to allow you to build an installable application in Javascript, HTML, and CSS. It also allowed you to make calls and pass JSON data from Javascript down to the native execution code, Objective-C for iOS and Java for Android.

My doctoral degree is now done. I could begin supporting that code set again but it would be better to implement it in Swift or current Objective-C and gain access to the new WebKit API  common to both iOS 8 and OS X Yosemite. Another reason to ‘start from scratch’ is that the new WKWebView is much more powerful that the old UIWebView. According to Apple, it has all the new HTML 5 abilities and now the same webkit engine as Safari so tools like QC Hybrid, PhoneGap, and the other hybrid tools are not needed by the vast majority of Hybrid developers. That was not true in the past. Never the less, I maintain that this type of project should, in most cases, be a temporary and stop-gap solution while you develop your app in the native languages of the platform. At least for now.

With all that history out of the way, lets get to a Swift code example.

For a hybrid application, the HTML, Javascript, CSS, and image files are included as part of the project just like any other file. This image shows the single-view Swift project I created for this posting. Also make sure you add the WebKit.framework to your project.


You can see I have a file called index.html. This is the file that the example code is going to load and trigger the loading of the main.css and main.js files just like any normal web page.

In the project’s ViewController.viewDidLoad() method I inserted added code to create a WKWebView, load index.html, and add the WKWebView to the main view.

(Note: This code example has been updated for Swift 2.0 on my gitHub repository.)

        //get a string path to the file
        var path = NSBundle.mainBundle().pathForResource("index",
                             ofType: ".html")
        //create a URL for the path
        var url = NSURL(fileURLWithPath:path)
        //create a request for the URL
        var request = NSURLRequest(URL:url)
        //create the WKWebView and set the size to match 
        //the window's full view 
        var theWebView:WKWebView = WKWebView(frame:self.view.frame)
        //have the web view load the page
        //add the web view to the main view

The reason I started the load before adding the web view was to get a little buffering going on before the display. The web view will load without being displayed.

I’m going to do another posting on how to communicate between Swift and Javascript in a later post. That has changed dramatically as well.

June 11, 2014

Swift, Operator Overloading, and Chaining Functions and Closures

Posted in iPhone development, mac development tagged , , , , , at 6:59 pm by tetontech

Swift makes it easy to overload existing or create new operators. In this post I’m going to show how to create an operator that allows functions and closures to be chained. That is, to pass the result of one function or closure call to another without embedding the second function call in the first and without storing the result of one function call and passing it to another.

Here are two simple functions that we will be playing with. There are much better ways to accomplish this simple task in Swift. I’ve only created these for use in this overloading and chaining example.

        func createMessage(an:String)->String{
            return an+" added"
        func toString(an:Int)->String{
            return "\(an)"

These functions can used together in two different traditional ways. One is to store each intermediate result in a variable and then use the variable.

        var numString = toString(5)
        var message = createMessage(numString)

Another way is to embed the calls inside each other.


Both of these approaches are completely valid. The first makes it easier to debug individual functions and see the order in which the functions are called. The second is more succinct but can cause a loss of understanding and call ordering in those new to programming. It can also become unintelligible if there are a large number of functions embedded within each other or if the ternary, ?:, operator is included in the calls.

An infix operator, one that appears between things like the standard + operator, can be useful in this type of situations. Other languages have what they refer to as a pipeline or piping operator, |>. If we were to create such an operator in Swift the function calls would look like this.


One advantage to this approach is that the call order of the functions is maintained. Another is it is succinct. Debugging individual functions using intermediate values is not possible without breaking up  the code but the stepwise debugger could be used instead.

The code for this new operator is small. Swift makes it easy to create using generic types.

1      //accept a value (left) and use it in the function (right)
2      operator infix |> { associativity left }
3      func |> <T,U>(left: T, right: T -> U) -> U {
4          return right(left)
5      }

Let’s take a look at each portion of the code.

Line 2 declares that we are creating an operator that will be an infix rather than a prefix or suffix operator. It will be used between to things instead of before or after. The ‘+’ operator is an infix operator with which you are familiar.

After declaring the creation of an infix operator the characters used as the operator, |>, are declared and properties of the infix are listed within the {} braces. The only property declared in this example is ‘associativity left’. This means that what is on the left side should be done before what is on the right. You could also indicate an operator precedence here if you desired. I decided not to at this point. This kept the example simpler.

Line 3 declares the function that is the operation to be executed. It lists the ‘|>’ indicator characters as the function name. It then declares two generic types T and U for later use. These must be placed inside the <> characters.

The footprint of the |> function comes next. It has two parameters, left and right. The left parameter is declared to be a singular value of some yet to be determined type T. The right parameter is declared to be a function that accepts this same type T as its only parameter and returns another yet to be determined type U. The |> function is then declared to return this same type of yet to be determined Type.

In our simple example, T is set to be Int and U to be String by the compiler. This is done for this line of code only. Some other line of code could use the |> operator with a completely different set of types for T and U.

Line 4 is the body of the function. It consists of passing the left parameter into the function that is the right parameter.

One of the nice things about  Swift is that functions are just closures bound to a name. This means that we can use the new operator with closures without needing to  modify it. Since we can use closures, we are able to capture values outside of the closure scope. This way we can have multiple parameters without having to overload the new operator. Here is an example that uses closures instead of the two small functions, toString and createMessage.

        var someString = " differently";
            (someNumber)->String in
                return "\(someNumber)"
            (a:String)->String in
                return a + " added" + someString

In the code above, we take advantage of the value capture ability of closures. Because we can use either closures or functions with our pipeline, |>, operator we don’t have to override it to accept multiple left-side parameters. Instead, when we need multiple parameters we can capture them in a closure instead.

In another post I’ll show how to overload this operator to pass a piece of data to an array of functions.


June 10, 2014

Swift Classes, Structs, Enums, and Tuples compared

Posted in Uncategorized tagged , , , , , , at 10:25 pm by tetontech

In Apple’s Swift book there is a chapter on Classes and Structs. The first major section of that chapter describes how Classes and Structs are the same and how they differ. There were a few things that they left out of the list. They also didn’t compare them to Enums and Tuples.

In this posting I’m going to display a table that compares all four types, but leaves out what Apple already has in their book. Including that information would clutter what I’m trying to get across. Please go look there to see more similarities and differences.







includes sizeof elements includes sizeof elements


by reference by value no passing by value


can have can have can contain functions and closures

contained values

as properties as properties as constants as elements

calculated properties

supported supported no no


The size row is the result of observing the results of calling the C sizeof() function on classes structs and enums. Tuples can’t be passed to sizeof() so that result is deduced.

Enumerations are not passed. All the other types are passed by value or reference as shown in the table. The only variance from this rule is Arrays. As said in the book, they are passed by reference until, not unless, a modification to the Array is made that changes its length. Then a copy is made and you are dealing with a copy.

The methods  row has a blank in the Enum column. Enums can’t have methods but they can contained pre-built switches that can be accessed (See Apple’s Swift book for details).

Calculated properties are somewhat like methods that are accessed by a property name. There is no data storage, only a return from a method call.

There are more of these, such as subscript support, that I’ll be adding to this table as I explore further.

June 9, 2014

Swift, Functional Programing, Structs and Fold

Posted in Uncategorized tagged , , , , at 10:08 pm by tetontech

In the last post I gave a pretty lame example of how to use fold. It was assembling a string from an array of numbers. Since the emphasis of that post was the source code for foldl and foldr I thought a lame but simple example would be OK. In this post I’m giving a computationally more significant example.

Let’s say you have an bunch of gerbils you are tracking and you need to know how many males and females there are. To simulate data input and storage routines outside the scope of this example let’s generate a series of pseudo-random gerbils and put them in an Array for later use.

    * example setup code
    var gerbils:Array<Gerbil> = []
    for index in 0...20{
        * arc4random returns a UInt32. Create an Int from it.
        let anAge = Int(arc4random() % 5)
        let aSex = Int(arc4random() % 2)
        * use Swift's ternary operator to change the aSex
        */ integer into the representative string
        gerbils.append(Gerbil(age: anAge, sex: aSex == 1 ? "female" : "male"))

     * Gerbil struct source
    struct Gerbil{
         var age:Int
         var sex:String

Now let’s take this Array of Gerbil structs and find out how many males and females there are. Either foldl or foldr would work so lets pick foldl. Swift’s standard reduce method would not work since reduce would require a Gerbil to be returned when given an Array of Gerbils. That doesn’t make sense here nor does that restriction make sense in most situations. That’s why we need fold methods for the Array class (See the previous post for the fold source code).

In this example foldl is passed an initial countBySex struct called statsWrapup that has both the male and female counts set to zero. Selecting zero for initialization makes it easy to increment the values, using Int’s ++ operator, when we find a male or female Gerbil. This detection and incrementation is done using Swift’s Ternary operator ?:

         * example begins
        var statsWrapup = gerbils.foldl(countBySex(males:0, females:0)){
            var (ageBySexTracker, aGerbil) = $0
            aGerbil.sex == "female" ? ageBySexTracker.females++ : 
            return ageBySexTracker
        println("females: \(statsWrapup.females) males: \(statsWrapup.males)")

         * countBySexStruct source
         struct countBySex{
            var males:Int
            var females:Int

There are many other choices that could have been made for this example. The sex indicator could have been left an Int with 0 or 1 potential values, the sex indicator could have been a boolean value with true for female and false for male, an Enumeration could have been created and used as the sex indicator, etc. but I chose not to do this for example clarity and to focus on why fold needed to be used instead of reduce.

Could this have all been done using a standard for loop? Of course. But why should we make that choice. It will increase the ‘glue’ code in our application that is written repeatedly and used rarely. It is well known that each line of code we write is a new potential bug. One way to reduce the bugginess of code is to stop creating code that is rarely used. By wrapping the looping code into a pre-exiting function, such as map, reduce, or fold, we execute the code many times. This can aid and speed debugging.

Next page

%d bloggers like this: