Obviously, swift looks much cleaner than it’s predecessor. Programmers with a background in modern programming languages such as python and ruby will hit less pain points when diving into iOS development.
Existing iPhone developers can say goodbye to square brackets and that irksome '@' symbol. In fact, the 'N' and 'S' keys on their new keyboards may even stay intact. But swift brings with it a wealth of new features beyond just a clean and modern syntax. I've spent a few days working with Apple's new programming language, and I've compiled a short list of new features that I’m excited to work with.
When first looking at swift code, you may notice some emphatic punctuation scattered throughout, namely, question marks and exclamation points. This isn’t a display of the programmer’s incompetence or excitement, but rather operations under swifts new ‘optionals’ system. Objective-C struggled in scenarios involving the absence of a value. Common solutions to this problem were utilizing Nil, nil, NULL, NSNull, NSNotFound, and -1. Obviously, this could get confusing when different libraries, frameworks, and even collaborators operated under a different philosophy or style. Swift aims to standardize this problem by the use of optionals. When declaring a new variable, you have the freedom to declare it as an optional variable. This is done by placing a question mark after the type.
var myOptional:String?
myOptional will hold the value nil until assigned otherwise. To access the value of myOpt, you will first have to check to make sure the value is not nil, and then you must ‘unwrap’ the value using an exclamation point. For example
var myVal:Int? = meaningOfLife() // Returns either an Integer or nil if myVal != nil{ println("The meaning of Life, the Universe, and Everything is \(myVal!)")}else{ println("Don't Panic")}
The exclamation point signifies that although the variable may be nil, you are absolutely sure it has a value at that moment.
When you first start programming in swift, you may notice Xcode intermittently placing question marks after some of your function calls. This isn’t the compiler questioning your ability as a programmer, it’s swift’s optional chaining system. Instead of nesting multiple 'if val != nil' statements, you can simply place a question mark after the optional value in a chained function call. If that value ends up being nil, the call will fail gracefully and return nil instead of throwing an exception.
Generics allow programmers to create functions, classes, and stucts with generic types. If you were inclined to create your own implementation of a Queue class in objective-C, you would have to create a separate class for every data type you intended to use with your Queue. You would need to create an NSStringQueue class for string queues, an NSNumberQueue class for number queues and so on. This would result in a huge duplication of code. The use of generics aims to solve this problem. We are now able to write code independently of type definitions. Creating a generic class is easy, and resembles the technique used in Java. Simply choose an identifier to act as a generic type for the class, and place it in angle brackets after the class name. That identifier now represents a generic type, and can be used anywhere in the class, structure, or function. Following through with our queue example, a generic queue class would look like this:
class Queue{ var values = Array() // creates an empty Array of Type 'T' func dequeue() -> T{ return values.removeAtIndex(0) } func enqueue(value:T){ values.append(value) } } // end class let fruitStack = Stack()// creates a new instance of Stack for Stack.enqueue("Apple")
Incidentally, this is how Array and Dictionary are implemented in swift, as may be evident by our declaration of the 'values' property.
Let’s say we want to be a little more strict on what we allow into our Queue class. In swift, we can restrict our generics to only allow data that conforms to a protocol. If we only wanted to only allow hashable object types into our queue (Types that conform to the Hashable protocol), we can do so with a colon.
class Queue<T:Hashable>{ … }
Swift introduces a new way to group data with tuples. Tuples are created by wrapping values in parentheses.
let blueJay = (3000,"blue",true)
This tuple contains Int, String, and Bool values. Although my Computer Science professors may disagree with the practice, tuples can be used as return types in functions, returning multiple values without declaring a new class or structure. Tuples are great to use as temporary values inside a limited scope. Tuples can also be used to declare multiple variables on a single line, thereby killing two birds with one stone. For example, in deconstructing the above tuple we can create several variables in one fell swoop.
let (feathers,color,canFly) = blueJay
If we only wanted to access a subset of the tuple, we can omit unwanted values with an underscore.
let (feathers,_,canFly) = (1500,"Red",true)
Here are a few more small features from swift that I find interesting or helpful:
enum StopLightColor{ case Red,Green,Yellow}var currentColor:StopLightColor = .Red // explicit declarationvar nextColor = StopLightColor.Green // inferred declarationcurrentColor = .Green // Only the Enumeration Value is requirednextColor = .Yellow
func sum(values:Int...) -> Int{ var total = 0 for val in values{ total += val } return total}sum(1,2,3,4,5,6,7) // Returns 28
for (index,val) in enumerate(someArray){ println("The Value \(val) is located at index \(index)")}
In conclusion, swift introduces a wealth of new features that should make iOS programming easier, cleaner, and a more enjoyable process.