Learning Swift

Now that Swift 3 is out and the language is stable, I thought I’d write my next app using it. I watched the first few videos of Paul Hegarty’s CS193P class and then started to read The Swift Programming Language (Swift 3). My first inclination, since this is the replacement for Objective C, was to relate the language features of Swift to those of Objective C. Both languages will have to handle strings and arrays so I started there. It didn’t go as well as I thought it would. An immutable string in Swift is initialized as

let mySwiftString:String = "This is a string."

whereas an immutable string in Objective C is initialized as

NSString *myObjCString = @[This is a string.];

So far so good, but the similarity breaks down quickly.

mySwiftString = "The string now has new content." //  Cannot assign to value: 'myString' is a let constant
myObjCString = "The string now has new content." //  No problem

Change the ‘let’ to ‘var’ for the Swift string and it works fine but then you no longer have an immutable string.

In Objective C, ‘myObjCString’ is an object created by the String Class. Swift strings are represented by the String type. In Swift, strings, arrays, dictionaries, sets, and numbers are value types.
When they are passed around, their value is passed around, not a reference to an object. Not so with Objective C where some of these are passed by value and some by reference. And numbers can be either ‘primitives’ or NSNumbers.

Another big difference is type safety. Swift is a type-safe language so you must explicitly define the type of everything or else the complier will object. Objective C puts the onus on you to make sure that the type of your object is what the code expects.

I quickly decided that trying to fit Swift into my mental model of Objective C wasn’t going to work. Sure they both handle operations, collection types, control flow, and classes, but their basic approach is so different that trying to draw analogies between the two is counter-productive.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.