If you just want to see my notes on the swift syntax bits and pieces that are novel to me, that are important aspects of swift and that I’m likely to forget then scroll down, otherwise continue reading for my first thoughts on functional programming.

I’ve finally got around to checking out Swift and along the way I got sidetracked by Functional Programming. I recognise that Swift is not a functional programming language but you can do functional programming in Swift in a way that is not possible in Objective-C.

Now that computer power is increasing mostly by adding CPU cores rather than increasing clock speed the need for programming tools that make it easier/safer/more reliable to work concurrently is more important than ever. Functional programming by removing state and passing immutable objects is far better at dealing with concurrency than object oriented programming. But I like state, I like objects that have properties that can change, that can receive messages and perform actions. I like thinking about how objects of the same and different types interact when it comes to creating something bigger. But there are issues of concurrency and multiple queues that working this way forces you to deal with, and every solution is a compromise.

I don’t think I’ll be giving up object oriented programming any time soon, but from now on I will be looking at any new problem with an eye to, how would I apply a functional programming solution to this problem. I’ve valued this diversion into functional programming. In particular I like the functional programming idea of looking for patterns, in things like function/method signatures. They can help to give the game away as to when things which you might think of as being different are similar or are actually be the same.

I like Rob Napier’s blog articles about functional programming. He is clear in his thinking and makes a concerted effort to strip his discussion about functional programming of its jargon. Actually there is more to it than that, he explains clearly. I realised this when I found myself going through his answers one by one on his stack overflow profile.

Rob Napier’s point that having functions whose output is only dependent on the input parameters means that fewer tests are needed than with object oriented programming to demonstrate that the output will be what you intend based on the inputs. The object oriented approach where objects hold state makes it much harder to demonstrate that the output for all inputs is what you intend.

I’m old enough to have started programming when procedural programming was the default paradigm which means that there are aspects of functional programming which are not foreign to me, but there is a big difference in mindset, staying away from mutable values is one, blocks are another.

In writing MovingImages I wrote a dictionary parser for creating CoreGraphics types like CGRects and creating CoreGraphic colors. The parser is made up of a bunch of procedural functions that hold no state, that take immutable objects, but are all written in Objective-C. My mindset was very much procedural when I was writing them. The parsing problem is very much one that lends itself to being solved within a functional paradigm and thinking about how I wrote the parser I don’t think it is a world away from being functional. Would I do it differently now? yes and I would use Swift to do it. The functional features in Swift make it a much better tool to solve this problem than Objective-C.

Now the first Swift feature I’d take advantage of when rewriting my dictionary parser would be enums with associated values. An enum with two cases, success and failure as described by @cocoaphony in his blog post Functional Wish Fulfilment though I’m not sure I’d use a NSError for the failure associated value.

enum Result<A> {
  case Success(Box<A>)
  case Failure(NSError)

My parser functions would return a Result object that I could get the result out of if no error occurred. Unfortunately this also requires a box class that can wrap up whatever A is into something the compiler can deal with. The box class looks like:

final class Box<T> {
  let unbox: T
  init(_ value: T) { self.unbox = value }

That is a messy implementation detail that hopefully will be fixed by the swift compiler team.

This introduces the final keyword which basically means that the class can’t be inherited from. The final keyword also has performance implications (instance method calling on a object which is declared final is faster). See Flex Monkey on inline performance. Using final on a method means the method can’t be overridden.

Swift syntax details I’m likely to forget, but that I will need


# Defining a class init and calling a constructor
class TipCalculator {
  init(total:Double, taxPct:Double) {
let tipCalc = TipCalculator(total: 33.25, taxPct: 0.06)


Declaring arrays and dictionaries

Note the various ways to declare array and dictionary types:

// [Double] is a shortcut for Array
// Declaring arrays and dictionaries with item types specified.
let newArrayImplicitDouble = [1.2, 1.3, 5.1, 0.1]
let newArray: Array = [1.2, 1.3, 5.1, 0.1]
let newArray2: [Double] = [2.3, 0.1, -0.8, 10.2, 153.7]
let dict: Dictionary<String, Double> = ["key1":1.2, "key2":-3.4]
let dict2: [String:Double] = ["key1":1.2, "key2":-3.4]


Obtaining a class from a string using a dictionary

If you want to be able to create a swift class from a string, you will need to use a lookup dictionary, as the Objective-C approach using NSClassFromString is not available. From this stack overflow answer.

# Creating a swift class from a string:
let classmapping: [String:String.Type] = ["string1":String.self]

if let stringClass = classmapping["string1"] {
    let theString = stringClass("A string")

The above currently crashes the swift compiler. There is a swift compiler bug which I’ve reported.

Swift compiler does implicit type

The Swift compiler will do everything it can to determine the type information it needs which means that you can leave a lot of explicit type information out. The following is variations on a theme demonstrating the different ways constants and variables can be declared. You can also often leave out named parameters and refer to a parameter by order. Named parameters also don’t need to have the type specified if it can be determined by the compiler elsewhere.

let intArray = [2, 9,4,5,3,2,11,17,16,4,1,3,0,23]
var evenArray = filter(intArray) { $0 % 2 == 0 }

evenArray = intArray.filter() { $0 % 2 == 0 }
let evenArray2: Array = filter(intArray) { (intVal: Int) -> Bool in intVal % 2 == 0 }



let twoTimesArray = intArray.map({$0 * 2})
let twoTimesStringArray = map(intArray, { (intVal: Int) -> String in String(intVal * 2) })
for theString in twoTimesStringArray {

let twoTimesStringArray2 = intArray.map({String($0 * 2)})
The Swift Tuple object

Swift also has a construct called a Tuple which can package up multiple values into a single object. The values can be assigned with names or be anonymous. That means a way to obtain the values from an anonymous tuple is required.

// Accessing elements of an anonymous tuple

let firstTuple = ("String 1", "String 2")
let firstItem = firstTuple.0
let secondItem = firstTuple.1
let (item1, item2) = firstTuple
let secondTuple: (String, Double) = ("Price", 25.99)
println("firstItem: \(firstItem), secondItem: \(secondItem), item1: \(item1), item2: \(item2)")

let namedTuple = (string1: "String 1", double1: 45.2)
println("string1: \(namedTuple.string1), double1: \(namedTuple.double1)")
A few optional notes

Optionals are really just a simple enum with two values (.Some and .None). Optionals can be created on demand, for example when a function/method is meant to return an optional we don’t have to return an optional instead we return a value or nil and the optional is automatically created for us wrapping the return value. Alexandros Salazar goes into some details about Optionals. This article by Natasha the Robot on unwrapping multiple-options is also useful. It’s kind of like wrapping the optionals up in a Tuple.

class Person {
    var residence: Residence?
class Residence {
    var numberOfRooms = 1

let john = Person()
// The following line will trigger a run time error.
// The ! forces the unwrapping of the optional.
let roomCount = john.residence!.numberOfRooms

// You can also check the validity of the optional through optional chaining before accessing.
if let roomCount = john.residence?.numberOfRooms {
    println("John's residence has \(roomCount) room(s).")
} else {
    println("Unable to retrieve the number of rooms.")

// You can assign an option the .None value.

let optional2: Int? = .None
Methods and functions can have named parameters

The external argument name can be different to the internal parameter name. Named parameters with swift functions Natasha Murashev aka the robot

func hello(fromName name: String) {
    println("\(name) says hello to you!")
hello(fromName: "Mr. Roboto")

If you want the external parameter name to be the same as the internal name, you don’t have to repeat the name, all you have to do is add a # to the front of the name in the function/method declaration.

The behaviour is different again for functions/methods declared in classes/structs/enums. The first parameter name is ignored, whilst all following named parameters don’t make a distinction between external and internal names. If you’ve forgotten the details I’d really recommend you go and read that article by Natasha again.

Declaring and implementing a class method, which are actually called Type methods:

class ClassWithClassMethod {
  class func classMethod() -> String
    return "My string"

I’d also recommend playing with Apple’s pattern matching playground which you access through the swift blog.

Instance Methods are Curried Functions in Swift

This blog post by Ole Begemann that Swift instance methods are curried functions is an eye opener. The following captures the idea of it, but I’d recommend reading Ole’s blog post.

class BankAccount {
    var balance: Double = 0.0
    func deposit(amount: Double) {
        balance += amount

let account = BankAccount()
account.deposit(100) // balance is now 100

let depositor = BankAccount.deposit // Notice the assignment to the method pointer.
depositor(account)(100) // balance is now 200

In the above case depositor is of type:

let depositor: BankAccount -> (Double) -> ()
Swift Namespaces

Namespaces in swift are implicit. All classes etc. are implicitly scoped by the module (Xcode Target) they are in. No class prefixes needed.

How are name clashes resolved? E.g. when I import a lib with Product class and have one myself?

You can always explicitly qualify with the module name. F.e., if you define a “swap” you can always get to “Swift.swap” as well.

The difference between objects created from a struct type and objects created from a class type is that objects instantiated from a struct are passed by value, whereas objects instantiated from a class are passed by reference. I’ve not seen anything that describes how to copy objects created from a class. The discussion in Apple’s developer documents doesn’t mention what you should do. My guess is that in Swift you’ll need something like the copy protocol in objective-c.