california app design company

Beyond Syntax: Why I'm Excited About Swift

October 03, 2014

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.

Optionals? Optionals!

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

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>{ 
 … 
} 

Tuples

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)

Swift Roundup

Here are a few more small features from swift that I find interesting or helpful:

  1. Enumerations with dot syntax. Dealing with enumerations is easier than ever in swift. Enumerations now adhere to dot syntax, meaning they are structured as {Enumeration Name}.{Enumeration Value}. As a bonus feature, if the compiler is aware of a variable's enumeration type, either through explicit declaration or inferred declaration, you can simply assign an enumeration value as just .{Enumeration Value}

enum StopLightColor{
    case Red,Green,Yellow
}
var currentColor:StopLightColor = .Red // explicit declaration
var nextColor = StopLightColor.Green // inferred declaration
currentColor = .Green // Only the Enumeration Value is required
nextColor = .Yellow

  1. Variadic Parameters. In swift your function declarations can take in a dynamic number of variables by use of the ‘...’ operator. Gone are the days of the nil terminated list. Inserting the ‘...’ after the variable type in the function declaration allows for a comma delimited list in the function call, and those values are congregated into a local array in the function body. As an example, If we wanted to make our own ‘sum’ function:

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

  1. Nested Comments. In swift you can create a comment block around an existing comment block without any compiler errors.

  2. Enumerate(). When constructing a ‘for in’ loop you can call the enumerate() function on the array and have access to both the value and index of that value.

for (index,val) in enumerate(someArray){
  println("The Value \(val) is located at index \(index)")
}

  1. Emoji. Have you ever felt the desire to make your code more fun and expressive of your personality? Me neither, nonetheless, swift allows for the use of emojis in everything from variable names to generic typing identifiers. At first I thought this was a pretty silly idea, but I’d be lying if I didn’t get a kick out of defining a U+1F419 class with U+1F42E and U+1F428 properties.

In conclusion, swift introduces a wealth of new features that should make iOS programming easier, cleaner, and a more enjoyable process.

is a Yeti Alum. A former software developer co-op at Yeti from Northeastern University's computer science co-op program.

blog comments powered by Disqus
Beyond Syntax: Why I'm Excited About Swift https://s3-us-west-1.amazonaws.com/yeti-site-media/uploads/blog/.thumbnails/214611036108_23f0e974c0_k_1.jpg/214611036108_23f0e974c0_k_1-360x0.jpg
Yeti (415) 766-4198 https://s3-us-west-1.amazonaws.com/yeti-site-static/img/yeti-head-blue.png