I’ve been writing a lot of Swift recently and really liking it (but sometimes really hating it). The strong-type nature can lead to some really unhelpful situations when coming at things from the perspective of weakly-typed languages like Objective-C.
Often times, I find myself looking at something in Swift and wondering, “What class is this object?” which is something with an easy answer in Objective-C:
[someObject class]
But in Swift, a different question becomes a lot more important: “Is this a certain type of class?”
let anObject = someObject as? SomeClass
Note that this assignment creates anObject, a variable of type SomeClass?, which is an Optional – specifically, a type of object that can potentially be nil. Swift is specific about non-optional types returning a value always, so Optionals must be used in situations where a nil value might be returned:
override func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath?
Notice that Apple expects this function to return an Optional NSIndexPath. According to Apple, this function “Tells the delegate that the specified row is now selected.” What happens if we want to do something, but not select the row? Simply return nil.
Since optional assignment can return nil, the assignment itself can be used as the argument of an if statement (something that I remember being excited about when learning PHP in high school). But this leads to a really easy use that I came up with today when implementing a custom isEqual method on a class I have been writing. It’s completely obvious if you are looking at things from the Swift perspective, but something that really just clicked for me today.
Here’s a way I might check for equality of a custom object in Objective-C:
-(BOOL) isEqual:(id)object {
if ( ![object isKindOfClass:[self class]] ) {
//test important, identifying features
if( object.property1 == self.property1 &&
object.property2 == self.property2 … etc) {
return YES;
}
}
return NO;
}
override func isEqual(object: AnyObject) {
if let someObject = object as? SomeClass {
//test important, identifying features here
if someObject.property1 == someObject.property2 etc {
return true
}
}
return false
}
Suddenly, it starts to make so much sense. I’m starting to see things that I have done for years in Objective-C work idiomatically the Swift way. A lot of it is super cool and really exciting to delve into as I get more comfortable with it.