// Range
let range1 = 0...2
let range2 = 0..<2
// Array
let arr1: [Int] = [1,2,3]
let arr2: Array<Int> = [1,2,3]
arr.first //=> Optional
arr[0] //=> value (maybe crash if wrong index)
arr[0...2] = [1,2,3]
arr[0...2] = [1,2,3,4,5] // still works
for item in arr {}
for (index, item) in arr.enumerated() {}
// Dictionary
let dic [String: Int] = ["alpha": 1, "beta": 2]
let dic Dictionary<String, Int>
dic["unknow"] //=> nil
for (key, value) in dic {}
for key in dic.keys {}
// Set
let set: Set<Int> = [1,2,3]
// Closure
var addClosure: (Int, Int) -> Int
// long form
addClosure = { (a: Int, b: Int) -> Int in
return a + b
}
// short form use type inference
addClosure = { (a, b) in
return a + b
}
// even shorter $0 = a, $1 = b
addClosure = {
return $0 + $1
}
// shortest - omit "return" if immediately return
addClosure = {
$0 + $1
}
// when closure is the last parameter
// common syntax
arr.filter { item -> Bool in
return !!item
}
var stock = [1.5: 5, 2.5: 10]
let sum = stock.reduce(0) { result, pair -> Double in
return result + (pair.key * Double(pair.value))
}
|