Scratching the surface of Swift

When Apple revealed Swift in June at the WWDC I wasn’t totally surprised, it felt like it wasn’t possible in the long run to continue with Objective-C. But mostly I was and happy! I was so sick and tired of Objective-C and I really got a reborn interest in building apps for iOS again. Also, the revealing of the upcoming Apple Watch made it impossible for me not to download the new Xcode version to try it out. This blog post will be the first of a couple of blog posts that will scratch the surface of the Swift programming language, just about enough to be able to use it when coding an app for iOS using Swift.

Variables

Swift is a statically typed language with a dynamic feeling. Thanks to type inference you don’t always have to declare the type because the language will know which type it is.

Declaring variables and constants

It is possible to explicitly declare that a variable is of type String but it is also fine to skip the type annotation and have Swift figure it out by just assigning a String to the variable.

var dogName: String = "Pluto"
var catName = "Kitty"

Using the keyword let instead of var will declare an immutable variable, i.e. a constant.

let horseName = "Jolly Jumper"

You can use a lot of different characters as variable names.

let π = 3.14159265359
let 💩 = "Poo"
Optionals

Optional is an awesome thing to use in case you need to work safely with something that may or may not have a value, e.g. a String that can have a text or be nil. An Optional String is not the same as a regular String because an Optional String can contain either a String or be nil and a regular String can never be nil. You use String? to declare an Optional String and you use String! to unwrap the Optional String to a regular String. You can also use an Optional when controlling flow since it returns true if it has a value.

let employeeName = findEmployeeNameById("AC6A55IJV84CE3979") // Function that may or may not return a value

if employeeName {
   print(employeeName!) // Unwrap the Optional using !
}

Another way of doing the above is to use an optional binding which removes the need for the forced unwrapping of the Optional. The conditional code is only executed if function findEmployeeNameById returned a value, and not nil.

if let employeeName = findEmployeeNameById("AC6A55IJV84CE3979") {
   print(employeeName)
}
Tuples

To group variables and create a compound value you can use a tuple.

let amountAndTax = (40, 10)
print(amountAndTax.0) // Will print 40
print(amountAndTax.1) // Will print 10
Type alias

It is possible to use a type alias if you want to refer to a type using a more descriptive name.

type alias HouseNumber = Int
var houseNumber: HouseNumber = 13

Functions

Functions in Swift are pretty straightforward and can take more or less any number of parameters, e.g. zero, one, multiple, or unknown number called a Variadic parameter.

Function taking no arguments
func printHelloWorld() {
   print("Hello World!")
}

printHelloWorld()
Function taking one argument
func printText(t: String) {
   print(t)
}

printText("Text")
Function taking two arguments
func printTexts(t1: String, t2: String) {
   print(t1 + t2)
}

printTexts("Text 1", "Text 2")
Function taking three arguments with external names

It’s possible, just like in Objective-C, to use external names on the parameters to make the purposes of each parameter more clear. I like this style of coding since it makes the function call more readable, but it for sure makes the code longer.

func concatText(text t1: String, withText t2: String, usingConcatSymbol symbol: String) {
   print(t1 + symbol + t2)
}

concatText(text: "Text 1", withText: "Text 2", usingConcatSymbol: " & ")
Function returning a value

To return a values the -> keyword is used after the parameter declaration

func concatText(text t1: String, withText t2: String, usingConcatSymbol symbol: String) -> String {
   return t1 + symbol + t2
}

var concatenatedText = concatText(text: "Text 1", withText: "Text 2", usingConcatSymbol: " & ")
// Will return "Text 1 & Text 2"
Default value for a parameter

A pretty neat feature is the possibility to have a default value for a parameter and offering anyone calling the function to skip that parameter.

func concatText(text t1: String, withText t2: String, usingConcatSymbol symbol: String = " : ") -> String { 
   return t1 + symbol + t2
}

var concatenatedText1 = concatText(text: "Text 1", withText: "Text 2")
// Will return "Text 1 : Text 2"

var concatenatedText2 = concatText(text: "Text 1", withText: "Text 2", usingConcatSymbol: " & ")// Will return "Text 1 & Text 2"
Returning multiple values

Another nice thing is that you can return multiple values from a function using a tuple type.

func calculateAmountAndTax(price: Double) -> (amount: Double, tax: Double) {
   return (price * 0.8, price * 0.2)
}

let amountAndTax = calculateAmountAndTax(price: 100.0) 
print("Amount is: " + amountAndTax.amount)
print("Tax is: + amountAndTax.tax)
Returning an Optional

Use the ? keyword to declare that the function may return nil.

func findEmployeeNameById(employeeId: String) -> String? { // Return Optional using ?
   for employee in employees { 
      if (employee.id == employeeId) { 
         return employee.name 
      } 
   }
   return nil
}
String interpolation

Using variables to create strings is actually ridiculously easy when using the powerful string interpolation feature.

func printHelloToPerson(withName name: String) { 
   print("Hello \(name)!")
}

printHelloToPerson(withName: "Roger Moore") // Will print "Hello Roger Moore!"

All right, that was it for the first post about Swift. In the next post I will look into some of the other interesting parts of Swift, such as classes, flow control, dictionaries, closures, generics, pattern matching…

Annonser

Kommentera

Fyll i dina uppgifter nedan eller klicka på en ikon för att logga in:

WordPress.com Logo

Du kommenterar med ditt WordPress.com-konto. Logga ut / Ändra )

Twitter-bild

Du kommenterar med ditt Twitter-konto. Logga ut / Ändra )

Facebook-foto

Du kommenterar med ditt Facebook-konto. Logga ut / Ändra )

Google+ photo

Du kommenterar med ditt Google+-konto. Logga ut / Ändra )

Ansluter till %s