Do you need help on a specific subject? Use the contact form (Request a blog entry) on the right hand side.

2015-01-30

Class variables

The languages I used most before the change to Swift were Objective-C and Java. When Apple announced swift, a modern OO language, one of my first "disappointments" with Swift were the missing Class variables.

In Java Class variables are simply defined by using the 'static' keyword. I.e.:

class MyClass {
    static int myClassVariable;

}

In Objective-C there was no direct class variable, we had to define them outside the class, and when visibility was an issue, they had to be hidden in an implementation file. A bit of a kludge if you ask me.

In Swift, the approach is very much like Objective-C, but the visibility problem is easily solved by using the 'private' keyword. Example:

private var myClassVariable: Int

class MyClass {
   ...

}

This approach has started to grow on me. I now like this better than the Java class variables. I find it more intuitive. After all, a class variable belongs to a class, but is not part of an object. Defining it outside the class makes this distinction clear in the code itself. The proximity with the class is still present because it has to be in the same file as the class definition.

While in the beginning I hoped that Apple would support class variables, I now think that this issue has become moot.

Edit 2015.04.05: In Swift 1.2 (comes with xcode 6.3) the "static" keyword can be used to define class variables just like in Java.

class MyClass {
    
    static var instanceCount: Int = 0
    
    init() {
        MyClass.instanceCount += 1
    }

}

Happy coding...

Did this help?, then please help out a small independent.
If you decide that you want to make a small donation, you can do so by clicking this
link: a cup of coffee ($2) or use the popup on the right hand side for different amounts.
Payments will be processed by PayPal, receiver will be sales at balancingrock dot nl
Bitcoins will be gladly accepted at: 1GacSREBxPy1yskLMc9de2nofNv2SNdwqH

We don't get the world we wish for... we get the world we pay for.

2015-01-28

Array's and for loops

At first glance, Swift offers a bewildering number of possibilities to iterate over an array in a for loop. The ones below are all the variations I could come up with.

This is probably the most used and simplest way to do this:

let values: Array<String> = ["one", "two", "three", "four"]

for value in values {
    println("value: \(value)")
}

Outputs:
value: one
value: two
value: three
value: four


In order to reverse the direction we can use the 'reverse' function:

for value in reverse(values) {
   println("value: \(value)")
}

Outputs:
value: four
value: three
value: two
value: one

So far, so good, but what if we also need the index within the loop? Well, Swift gives us the 'enumerate' function:

for (index, value) in enumerate(values) {
    println("index: \(index), value: \(value)")
}

Outputs:
index: 0, value: one
index: 1, value: two
index: 2, value: three
index: 3, value: four


And can we stack the reverse on the enumerate? Yes we can, but with a gotcha:

for (index, value) in enumerate(reverse(values)) {
    println("index: \(index), value: \(value)")
}

Outputs:
index: 0, value: four
index: 1, value: three
index: 2, value: two
index: 3, value: one


See the gotcha? the index does not reverse, it still counts from 0 to count-1! This is probably because the enumerate function creates the index, not the reverse function. As far as the enumerate is concerned, it still counts up. Note that it is not possible to call the reverse on the result of the enumerate function. (i.e. reverse(enumerate(values)) does not compile)


When we need the index to reverse as well, we can use the old model for loop:

for var index = values.count; index > 0; {
    let value = values[--index]
    println("index: \(index), value: \(value)")
}

Outputs:
index: 3, value: four
index: 2, value: three
index: 1, value: two
index: 0, value: one

Note that in the above the ';' before the loop is necessary to create an empty statement before the loop starts. Also note that the first use of the index must have the '--' operator in front of it, and this is in fact part of the loop maintenance. I find this a bit ugly, but it does work. We can also write this as follows:

for var index = values.count - 1; index >= 0; --index {
    let value = values[index]
    println("index: \(index), value: \(value)")
}

Outputs:
index: 3, value: four
index: 2, value: three
index: 1, value: two
index: 0, value: one

but personally I find this code even uglier.

I would rather use the newer methods:

let values: Array<String> = ["one", "two", "three", "four", "five"]

for index in 0 ..< values.count {
    let value = values[index]
    println("index: \(index), value: \(value)")
}

Outputs:
index: 0, value: one
index: 1, value: two
index: 2, value: three
index: 3, value: four
index: 4, value: five

or:

for index in 0 ... values.count - 1 {
    let value = values[index]
    println("index: \(index), value: \(value)")
}

Outputs:
index: 0, value: one
index: 1, value: two
index: 2, value: three
index: 3, value: four
index: 4, value: five

These can also be used with the reverse function:

for index in reverse(0 ..< values.count) {
    let value = values[index]
    println("index: \(index), value: \(value)")
}

Outputs:
index: 4, value: five
index: 3, value: four
index: 2, value: three
index: 1, value: two
index: 0, value: one

Note that this index does count down!


There are also the 'stride:from:to:by' and 'stride:from:through:by' functions which can be used to step in other increment than 1. These can also be used to step through in the reverse direction by specifying a negative value for the 'by' parameter.

let values: Array<String> = ["one", "two", "three", "four", "five"]

for index in stride(from:0, to:values.count - 1, by:2) {
    let value = values[index]
    println("index: \(index), value: \(value)")
}

Outputs:
index: 0, value: one
index: 2, value: three


for index in stride(from:0, through:values.count - 1, by:2) {
    let value = values[index]
    println("index: \(index), value: \(value)")
}

Outputs:
index: 0, value: one
index: 2, value: three
index: 4, value: five

The 'through' variant is inclusive, the 'to' variant is exclusive, similar to '...' and '..<'

Quite a lot of possibilities, which one you use will of course depend on what you need. In general I would avoid the old syntax, it just does not seem to offer any advantage when iterating over an array.
At the end, I leave you with a list of all the possibilities presented above, first the forward loops, then the reverse loops (all in steps of 1 or -1 and all loop over the entire array):

for value in values { ... }
for (index, value) in enumerate(values) { ... }
for index in 0 ..< values.count { let value = values[index]; ... }
for index in 0 ... values.count - 1 { let value = values[index]; ... }
for index in stride(from:0, to:values.count, by:1) { let value = values[index]; ... }
for index in stride(from:0, through:values.count-1, by:1) { let value = values[index]; ... }
for var index = 0; index < values.count; index++ { let value = values[index]; ... }

for value in reverse(values) { ... }
for (index, value) in enumerate(reverse(values)) { ... }  // index does NOT reverse!
for index in reverse(0 ..< values.count) { let value = values[index]; ... }
for index in stride(from:values.count - 1, to:-1, by:-1) { let value = values[index]; ... }
for index in stride(from:values.count - 1, through:0, by:-1) { let value = values[index]; ... }
for var index = values.count; index > 0; { let value = values[--index]; ... }
for var index = values.count - 1; index >= 0; --index { let value = values[index]; ... }

Happy coding...

Did this help?, then please help out a small independent.
If you decide that you want to make a small donation, you can do so by clicking this
link: a cup of coffee ($2) or use the popup on the right hand side for different amounts.
Payments will be processed by PayPal, receiver will be sales at balancingrock dot nl
Bitcoins will be gladly accepted at: 1GacSREBxPy1yskLMc9de2nofNv2SNdwqH

We don't get the world we wish for... we get the world we pay for.

2015-01-27

Variadics

Variadics are a neat trick to pass an unknown number of parameters of a single type to a function.
While you could use arrays or dictionaries to do the same, it looks better if you can do it as a variadic parameter.

A variadic parameter is specified as follows:

    func objectAtPath(path: String...) -> MyDataClass? {...}

Unfortunately it cannot be used for multiple types. For that you will need to use an Array or a Dictionary.

Inside the function it is used as if the variadic parameter was an array:

    if path.count == 0 { return nil }

    let name = path[0]

It is not possible to pass the parameter through to functions that are called from with the function that takes it as a parameter, specifically the following is NOT possible:

    if path.count == 0 { return nil }

    let name = path[0]
    
    return objectAtPath(path[1..<path.count])

Which is a pity as functions with a variadic parameter will often be perfect candidates for recursive calls.

Maybe Apple will add this kind of functionality in future version, but for now we need to work around this. It can be done by creating one version of the function that takes an array and one that uses the variadic parameter. The one with the variadic can then call the one with the array, like this:

    func objectAtPath(path: Array<String>) -> MyDataClass? {...}

    func objectAtPath(path: String...) -> MyDataClass? { return objectAtPath(path) }

You can then choose whether to use:

    let name = objectAtPath(["root""level1", "level2"])

Or the slightly better looking:

    let name = objectAtPath("root""level1", "level2")

Happy coding...

Did this help?, then please help out a small independent.
If you decide that you want to make a small donation, you can do so by clicking this
link: a cup of coffee ($2) or use the popup on the right hand side for different amounts.
Payments will be processed by PayPal, receiver will be sales at balancingrock dot nl
Bitcoins will be gladly accepted at: 1GacSREBxPy1yskLMc9de2nofNv2SNdwqH

We don't get the world we wish for... we get the world we pay for.

2015-01-25

Apple System Log Facility

The Apple System Log facility does not seem to be very wel known, but it is a very useful logging tool. For help during debugging as well as to help users when they encounter problems. Unfortunately apple seems to have forgotten to include ASL in Swift as of Xcode 6.1.1.

Its not too difficult to use ASL from Swift though. It can be done the following way:

Create a file "asl-bridge.h" with the following content:

#import <asl.h>
#import <Foundation/Foundation.h>

#ifndef SwiftFire_asl_bridge_h
#define SwiftFire_asl_bridge_h

int asl_bridge_log_message(int level, NSString *message);


#endif

Then add the implementation "asl-bridge.m":

#import <Foundation/Foundation.h>

#import <asl.h>
#import "asl-bridge.h"

int asl_bridge_log_message(int level, NSString *message) {
    return asl_log_message(level, "%s", [message cStringUsingEncoding:NSUTF8StringEncoding]);

}

In the MyProject-Bridging-Header.h include the following:

#import "asl-bridge.h"
#import <asl.h>

The above includes the ASL headers you need, and provide an interface for the logging function without generating a "unsafe" warning.

Since I don't like how the log levels in objective-c are defined I have also created a more Swifty-er log level enum definition:

enum LogLevel: Int {
    case DEBUG      = 0
    case INFO       = 1
    case NOTICE     = 2
    case WARNING    = 3
    case ERROR      = 4
    case CRITICAL   = 5
    case ALERT      = 6
    case EMERGENCY  = 7
    case NONE       = 8
    func toString() -> String {
        switch self {
        case .DEBUG:     return "DEBUG    "
        case .INFO:      return "INFO     "
        case .NOTICE:    return "NOTICE   "
        case .WARNING:   return "WARNING  "
        case .ERROR:     return "ERROR    "
        case .CRITICAL:  return "CRITICAL "
        case .ALERT:     return "ALERT    "
        case .EMERGENCY: return "EMERGENCY"
        case .NONE:      return "NONE     "
        }
    }
    func toAslLevel() -> Int32 {
        switch self {
        case .DEBUG:     return 7
        case .INFO:      return 6
        case .NOTICE:    return 5
        case .WARNING:   return 4
        case .ERROR:     return 3
        case .CRITICAL:  return 2
        case .ALERT:     return 1
        case .EMERGENCY: return 0
        case .NONE:      return -1
        }
    }
}

Finally we get to define the function I actually use for logging:

    private func logAslFacility(level: LogLevel, message: String) {
        asl_bridge_log_message(level.toAslLevel(), message)
    }

Edit: See also part 2

Added 2015-05-08: To see the above in action (and more), check out my github project "SwifterLog" in the upper right corner of this page.

Happy coding

Did this help?, then please help out a small independent.
If you decide that you want to make a small donation, you can do so by clicking this
link: a cup of coffee ($2) or use the popup on the right hand side for different amounts.
Payments will be processed by PayPal, receiver will be sales at balancingrock dot nl
Bitcoins will be gladly accepted at: 1GacSREBxPy1yskLMc9de2nofNv2SNdwqH

We don't get the world we wish for... we get the world we pay for.

2015-01-23

The GeneratorType and SequenceType protocols

It can be very useful to be able to iterate over the content of your objects. For this, Swift provides the SequenceType protocol, which in turn needs the GeneratorType protocol.

When you implement the SequenceType protocol you can iterate over the data in your object as follows:

    for x in objectOfMyClass {
        ... process x
    }

The SequenceType protocol is simple:

protocol SequenceType : _Sequence_Type {
    typealias Generator : GeneratorType
    func generate() -> Generator
}

It needs just one function that returns an object which implements the GeneratorType protocol. It can be tempting to return "self" as the generator. And that will indeed work, ... a little. It is however dangerous  as you have no protection against multiple uses of the same generator, for example with nested loops or object access from multiple threads. A safer approach is to create a unique generator object on each call to the generate function. Still, even then, writing a safe generator can be a bit daunting as you need to think about mutations that could occur while you are iterating over your internal data.

The GeneratorType protocol is also very simple, you just have to implement one function:

protocol GeneratorType {
    typealias Element
    mutating func next() -> Element?
}

Here is an implementation that I think is relatively robust:

class MyDataClass {
    var myData = "data"
}

class MyClass: SequenceType {
    
    func values() -> Array<MyDataClass>? { return ... }
    
    struct MyClassGenerator: GeneratorType {
        
        typealias Element = MyDataClass
        
        // The object for which the generator generates
        let source: MyClass
        
        // The objects already delivered through the generator
        var sent: Array<MyDataClass> = []
        
        init(source: MyClass) {
            self.source = source
        }
        
        // The GeneratorType protocol
        mutating func next() -> Element? {
            
            // Only when the source has values to deliver
            if var values = source.values() {
                
                // Find a value that has not been sent already
                OUTER: for i in values {
                    
                    // Check if the value has not been sent already
                    for s in sent {
                        
                        // If it was sent, then try the next value
                        if i === s { continue OUTER }
                    }
                    // Found a value that was not sent yet
                    // Remember that it will be sent
                    sent.append(i)
                    
                    // Send it
                    return i
                }
            }
            // Nothing left to send
            return nil
        }
    }
    
    typealias Generator = MyClassGenerator
    func generate() -> Generator {
        return MyClassGenerator(source: self)
    }
}

This implementation keeps track of mutations that can occur in the source class and will respect these mutations on subsequent calls to "next()". Hence updates being made to a MyClass object will be respected. For example deleting MyDataClass objects that have been sent already will not upset the for loop, nor will removing MyDataClass objects that have not been sent yet result in "next()-ing" data that is not present anymore.

Happy coding ...

Did this help?, then please help out a small independent.
If you decide that you want to make a small donation, you can do so by clicking this
link: a cup of coffee ($2) or use the popup on the right hand side for different amounts.
Payments will be processed by PayPal, receiver will be sales at balancingrock dot nl
Bitcoins will be gladly accepted at: 1GacSREBxPy1yskLMc9de2nofNv2SNdwqH

We don't get the world we wish for... we get the world we pay for.

2015-01-21

Null, nil and pointers

Note: This article is obsolete for the later versions of Swift.

Optional in Swift have made the use of "non-existing" values easier and safer. However sometimes things can get confusing at the low level APIs that use pointers to pointers.

In most instances we can now use nil were previously null was used.

For example in this API:

func URLForDirectory(_ directoryNSSearchPathDirectory,
            inDomain domainNSSearchPathDomainMask,
   appropriateForURL urlNSURL?,
              create shouldCreateBool,
               error errorNSErrorPointer) -> NSURL?

The appropriateForURL parameter is specified as an optional and can thus safely be specified as a nil.

This call also makes use of the error parameter, which is specified as a NSErrorPointer. This behaves very much like an optional, even though it is not. We can use nil here as well if we do not want to use the error parameter.

At lower level APIs nil is usable as well, for example:

func getaddrinfo(_: UnsafePointer<Int8>,
                 _: UnsafePointer<Int8>,
                 _: UnsafePointer<addrinfo>,
                 _: UnsafeMutablePointer<UnsafeMutablePointer<addrinfo>>) -> Int32

In the first parameter in this function nil can be used, but in the last parameter we may want to use a pointer to a nil, which I have not found possible to construct. But there is a way out, the pointer definitions include a ".null()" function which returns a null-pointer.

In the above example we can pass a pointer to a nul pointer by doing it like this:

    // For the result from the getaddrinfo
    
    var servinfo = UnsafeMutablePointer<addrinfo>.null()
    
    
    // Get the info we need to create our socket descriptor
    
    status = getaddrinfo(
        nil,                        // Any interface
        servicePortNumber,          // The port on which will be listenend
        &hints,                     // Protocol configuration
        &servinfo)                  // The created information

Now the getaddrinfo function has a pointer to a null pointer which it can update to provide the requested information.

As mentioned before, be sure to define the reference servinfo as a 'var' not as a 'let'. Otherwise the '&' won't work.

Happy coding...

Did this help?, then please help out a small independent.
If you decide that you want to make a small donation, you can do so by clicking this
link: a cup of coffee ($2) or use the popup on the right hand side for different amounts.
Payments will be processed by PayPal, receiver will be sales at balancingrock dot nl
Bitcoins will be gladly accepted at: 1GacSREBxPy1yskLMc9de2nofNv2SNdwqH

We don't get the world we wish for... we get the world we pay for.

2015-01-19

NSError

2015-09-18: See my follow up post for the Swift 2.0 changes.

Sooner or later every developer will need to use an API with an NSErrorPointer in it.

For example when reading a file:

String(contentsOfFile: String,
       encoding: NSStringEncoding,
       error: NSErrorPointer)

It's not difficult to use, but if you are like me, the first time I raised my eyebrows, I was not expecting to use pointers in Swift. How do we do that?

Like most stuff, its really simple, once you know how:

var error: NSError?
let content = String(contentsOfFile: myPath,
                     encoding: NSUTF8StringEncoding,
                     error: &error)

It is important to define 'error' as a 'var', turns out that we cannot use pointers for variables created with 'let'. Even when you never intent to change the value. Also, do not assign a value to 'error', though you can assign 'nil' if you like (but the compiler will do it for you).

The API call will create an error for us if it needs to. After the API call, the 'error' will be non-nil if an error occurred.

For evaluation we use the error var as follows:

   // Read the file into a string
        
   var error: NSError?

   let content = String(contentsOfFile: path,
                        encoding: NSUTF8StringEncoding,
                        error: &error)

   if let message = error?.localizedDescription {
      println(message)
      return nil
   }

   return content

Happy coding...

Did this help?, then please help out a small independent.
If you decide that you want to make a small donation, you can do so by clicking this
link: a cup of coffee ($2) or use the popup on the right hand side for different amounts.
Payments will be processed by PayPal, receiver will be sales at balancingrock dot nl
Bitcoins will be gladly accepted at: 1GacSREBxPy1yskLMc9de2nofNv2SNdwqH

We don't get the world we wish for... we get the world we pay for.