Training and Instructional Design
It came to my attention this week there’s a big change to Swift code on the way. It doesn’t look big though: it is the difference between as
and as!
.
The keyword as
is the conversion operator. Usually type or class are easily defined like this:
var myColor = UIColor() //class UIColor var myNumber:Integer = 0 //type Integer
But there are times you get things like this in table views and collection views:
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
The method of dequeueReusableCellWithIdentifier
returns AnyObject
, which is so generic it is worthless. We need to downcast it to UITableViewCell
to use it.
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as UITableViewCell
If the class does not exist or the class is incompatible with the cast, you get an error. For documentation purposes, Apple changed as
to as!
for these cases so anyone reading your code knows an error could occur. In Swift 1.2 Beta this should be
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! UITableViewCell
This does not work before 1.2 though. Don’t try it unless you have a Xcode 6.3 beta.
Speaking of betas, I want to be clear about my policy about betas:
Unless there is no production version, I always write to the production version. I suggest unless you seriously know what you are doing and don’t care to actually get something in the App Store quickly to avoid beta versions. There are four reasons for this:
So I make it a policy not to use betas unless I have to. I did between June 2014 and October 2014 because there was nothing else for Swift. And I had to change this entire website several times because of that. I could delay my book launch for months due to this change, or use the production version and get it out in March. Those working on Apple watch projects as of this writing have to use a beta. They have no choice. If you have a choice of beta and a production version, Pick the production.