Yesterday, Apple published a new blog post, announcing the release of XCode 6.3 beta and iOS 8.3 beta. Apart from some welcomed performance and stability improvements, the release includes some changes to the Swift language itself, which is now in its 1.2 version. These changes add some really cool features, and also some incompatibilities with previous versions, so I think it’s worth mentioning some of them:

Failable casts now must be explicitly declared

Swift takes great pride in its type-safety nature, and rightly so. However, one of the most dangerous structures of the language is forcing a downcast of an object to a certain type. In the past, you would have something like this:

var data: AnyObject! = SomeNetworkClass.someDataRetrievalMethod()
let imageData = data as NSData
let image = UIImage(data: imageData)

However, if you received, say, a null object (or any other object non transformable to NSData), the cast would fail and probably crash the program as soon as it’s used. Now, you must explicitly declare that the downcast is failable, making a good visual clue for the developer(s).

var data: AnyObject! = SomeNetworkClass.someDataRetrievalMethod()
let imageData = data as! NSData
let image = UIImage(data: imageData)

You can still use as “as is” in upcasts, though.

❤️ Enjoying this post so far?

If you find this content useful, consider showing your appreciation by buying me a coffee using the button below 👇.

Buy me a coffeeBuy me a coffee

Enum types get the @ObjC treatment

I really love enums in Swift, I think they are clear, useful and more powerful than its Objective-C counterparts, but one of the more frustrating things about them was their inability to be exported and used in Objective-C code. I think most of us, iOS/OSX developers live today in a limbo between the two languages (specially if you are maintaining old code/apps), so proper interaction between them is essential. Now, you can use the @objc attribute with your favorite Swift enum, and get it ready to rock on your .m files, so now:

@objc enum Drink: Int {
   case Beer, Wine, Whisky, Vodka
}

becomes:

typedef NS_ENUM (NSInteger, Drink) {
   DrinkBeer, DrinkWine, DrinkWhisky, DrinkVodka
}

Lazy instantiation of constants

One of my favorite changes! I always try to define my attributes as constants with the let keyword for optimization and clarity, but sometimes its initialization depends on some factors that just are not clear when you are defining them, so I sometimes end up turning them into vars. Now, with Swift 1.2, you can declare a constant with no value and initialize it later, as long as you don’t modify its value afterwards:

let resultMessage: String
if let entries = SomeNetworkClass.getCollectionData() as? [Entry] {
   resultMessage = "I collected \(entries.count) items from the network"
} else {
   resultMessage = "An error happened while retrieving the entries..."
}
userInterface.showResultMessage(resultMessage)

Unwrap all your gifts at once

One of the most painful constructs in Swift happens when unwrapping a set of values (probably received from a REST API or a JSON server response) that you need to check one by one. Sometimes, some of the attributes are so closely related that you can’t help but check them in cascade, forcing you to write this typical overblown nested structure:

if let attr1 = data["name1"] as? Type1 {
   if let attr2 = data["name2"] as? Type2 {
      if let attr3 = data["name3"] as? Type3 {
         ...
      }
   }
}

Luckily, now we can write something as this:

var things: [AnyObject] = ["I am a string!", 34234, 543.123, NSDate()]
if let first = things[0] as? String, second = things[1] as? Int, 
   third = things[2] as? CGFloat, fourth = things[3] as? NSDate {
    println("Got a valid response <\(first), \(second), \(third), \(fourth)>")
}

Let it be… compared

Now the “if let” construct also allows for condicional comparision of the multiple unwrapped values, like in this case:

if let a = numberOfEntriesInCache(), b = numberOfEntriesFromServer() where a < b, let c = updateNeeded() {
   doSomethingCoolToUpdateTheUI()
}

Set joins the family!

Yay! Ever since the initial release of Swift, I fell in love with Arrays and Dictionaries, but missed an equivalent for Cocoa’s NSSet. Well, it seems Apple has decided to add the new type, thank you Apple! Now, we have all of our beloved NSSet functionalities in a sexy Swift basic type:

var aSet: Set<String> = []
aSet.insert("Hello")
aSet.insert("World!")
aSet.insert("Hello")
println("\(aSet)") // prints ["World!", "Hello"], "Hello" isn't included twice
var bSet: Set<String> = []
bSet.insert("Hello")
println("bSet is a subset of aSet? \(bSet.isSubsetOf(aSet))") // prints bSet is a subset of aSet? true

I’m still trying to figure out what’s the proper abbreviated syntax for Sets, so if you know something about it, let me know in the comments.

Edit: after some research and some help from the forum, I found an abbreviated syntax that keeps code simple and elegant:

var aSet: Set = ["One thing", "Another thing"]

 

And many, many more…

Swift 1.2 also includes lots of other changes, mainly related with optimization and interaction with Objective-C/C. Make sure to check them out!