Swift For Dummies
Book image
Explore Book Buy On Amazon

This is a list of tips, typos, and gotchas from switching between Objective-C and Swift. It doesn't take long to make the transition, but it’s easy to get stuck on this:

  • Types follow variable and constant names: Double myDouble in Objective-C, but myDouble: Double in Swift.

  • Type casting uses function syntax not type syntax: (Double*)myDouble in Objective-C but Double(myDouble) in Swift.

  • There are no collection sets in Swift, but there are arrays and dictionaries.

  • Dictionaries and arrays have a single type because there’s no base class like NSObject. Create a common base class to use a variety of classes in an array or dictionary.

  • Compile errors are flagged on different lines in Swift than in Objective-C. (This is for those cases where the syntax is in error and the compiler has to do its best. If you’re used to the way Objective-C behaves in these strange cases, be aware that Swift sometimes behaves differently.)

  • Swift subscripts can replace custom accessors or getters more efficiently.

  • Use generic function type name placeholders (often T) for swapping and comparing two objects of the same type.

  • Optionals are their own types. Int? is not the same type as Int.

  • Swift infers types from your data. When it comes to inference in an expression, Int together with Float using any operator = Double.

  • Use _ in case statements and patterns as in this code. Test it in a playground and switch the values at the top:

var myValue = 5
var myTest = 50
var myTest2 = 100
switch (myTest, 75) {
case (_, 100):
println ("skipping")
case (50, _):
 println ("myValue")
 println ("Default")

About This Article

This article is from the book:

About the book author:

Jesse Feiler is a developer, consultant, and author specializing in Apple technologies. He is the creator of Minutes Machine for iPad, the meeting management app, and Saranac River Trail and is heard regularly on WAMC Public Radio for the Northeast’s The Roundtable.

This article can be found in the category: