Swift Tutorial

Apple hosted a swift tutorial for the HackGT this weekend. It was workshop that Apple’s Engineers teach us to wirte a simple iOS app on swift. Here is some notes for reference.

Optionals

optionals are a wrapper that allow a variable to contain nothing at all -> a nil

var attendee: Person?
var myString ="xys"
var possibleInt: Int? myString.toInt()
// possibleInt == nil, and it's safe

myString = "7"
possibleInt = myString.toInt() // possibleInt == 7, and it is safe

Optional Binding

use let with if-else/ while statements to simplify unwrapping value contained in optional

aString = ...
if let actualNumber = aString.toInt() {
     println("\(actualNumber)")
} else {
    println("the string could not be converted into a integer")
}

//or use 
actualNumber != nil


var randall: Person? = nil

randall?.sudoMakeMeASandwich()
// essentially equal to .. 
if randall != nil {
    randalll!.sudoMakeMeASandwich() // you need a '!' to unwrap it. 
}

while app crash is a preferable situation. initial as a nil, and it should be initial success. and if this item init fail, should make it crash.

// implicitly-unwrapped optional declaration uses !
var itemName: String!

Segue

  • transition from one scene to another
  • initiated programmatically or set up in storyboard
  • typically has an identifier
  • perform setup in prepareForSegue(_:sender:)