Swift Memo

Swift Memo
This memo is for Swift learning memo.
This is from Swift Guide Tour

Memo list


Variable

let is constant, never changed.
var is variable, you change value including type.

let a = 10
var b = 10

Optional

This is good example from Apple Developer

let possibleString: String? = "An optional string."
let forcedString: String = possibleString! // requires an exclamation mark
 
let assumedString: String! = "An implicitly unwrapped optional string."
let implicitString: String = assumedString // no need for an exclamation mark

? : Optional nil is fine
! : nil isn’t fine

Optional var is wrapped variable, you can’t use directly, and you need to unwrap to add ! after var name.

a!.test()   // Forced unwrap(if nil, happens runtime error)
a?.test()   // Optional unwrap(if nil, returns nil)
var a : Int?   // Optional, default is nil
var b : Int    // Not Optional, no initiallization
var c: Optional<Int> // Optional

Method

func resStr() -> String {
   return "Hello"
}
    
func updatenum(vals : [Int]) -> (num1: Int, num2: Int) {
   var num1 : Int! = vals.count
   var num2 : Int! = vals.first
   return(num1, num2)
}
    
func sum(numbers: Int...) -> Int {
   var total = 0;
   for number in numbers {
      total += number
   }
   return total
}
    
func resFunc() -> (Int -> String) {
   func resStr(number: Int) -> String {
      return  String(number)
   }
   return resStr
}

Return method method.


Class

No template from XCode?

class

import Foundation

class Sample {
    var num = 0   
    func resStr() -> String {
        return "Hello"
    }

    class func staticm() -> String {  // static
        return "I am static"
    }
}
var sample = Sample()
sample.num = 3
println(sample.num)
let str = sample.resStr()
println(str)

* If you want to use class as Framework, you should add public.

constructor

override public init() {
   super.init()
}

Array, Dictionary

Sample

func dictarrayTest() {
   var arrays = ["Yoona", "Sooyong", "Taeyon"]
   var dics = ["1" : "Yoona", "2" : "Taeyeon"]
        
   println(dics["1"])
   println(arrays[0])
        
   // Empty
   let emptyArray = [String]()
   let emptyDictionary = [String: String]()
   let emptyArray2 = []
   let emptyDic = [:]
        
   var mutableArray = [String]()
   mutableArray.append("Yoona")
   println(mutableArray[0])
   var mutableDic = [String : String]()
   let value : String! = "yoona"
   mutableDic.updateValue(value, forKey: "1")
   println(dics["1"])

   for (key,value) in mutableDic {
            println("Key:" + key + "Value:" + value)
   }
}

Result

Optional("Yoona")
Yoona
Yoona
Optional("Yoona")
Key:1Value:yoona

Power up switch

We can evaluate String class.
Also use method. Like if else

 func powerSwitch(name : String) {
        switch name {
        case "Yoona":
            println("You are Yoona")
        case "A", "S":
            println("You use Code Name")
        case let x where x.hasPrefix("Mr."):
            println("Mr.")
        default:
            println("others")
        }
}

Access

Use .

let skView = self.view as SKView
skView.showsFPS = true
skView.showsNodeCount = true

Others

No header.


For, each

for touch: AnyObject in touches {
}
for var i=0; i < 10; i++ {
}