計算型屬性(computed property)swift
var valueT: Double { get {//get方法在讀值的時候調用 return NSNumberFormatter(). numberFromString(labelText.text!)!.doubleValue } set {//set方法在賦值的時候調用 labelText.text = 「\(newValue)」//newValue即get中return的值 } } Declaration var valueT: Double { get set } Declared In ViewController.swift
閉包(closure): 用來接收參數和返回參數,相似於函數,可是沒有函數名閉包
var operators: String = 「/「, num1 = 2.0, num2 = 1.0, answer: Double! func operatorOnTheNum(operators: (Double, Double) -> Double ) -> Double { return operators(num1, num2) } switch operators { case "+": answer = operatorOnTheNum {$0 + $1}//opaeratorOnTheNum({(opt1: Double,opt2: Double) -> Double in return opt1 + opt2 })的極簡形式 case "-": answer = operatorOnTheNum {$0 - $1} case "*": answer = operatorOnTheNum {$0 * $1} case "/": answer = operatorOnTheNum {$0 / $1} default: break }
mutating:在結構體和枚舉這兩種類型中,實例方法只有經過mutating才能夠屬性的。函數
protocol Togglable { mutating func toogle() } enumeration OnOffSwitch: Togglable { case Off, On mutating func toogle() { switch self { case On: self = On case Off: self = Off } }
@auto_closurecode
func simpleAssert(x: Bool) { let a = 0 if a & x { …… } else { …… } } simpleAssert(someExpensiveComputation() !=42) **當咱們經過上述代碼調用simpleAssert函數是,咱們不得不每次都須要調用someExpensiveComputation ()!=42的值是真是假,那麼怎麼樣能作到延遲求值。** func simpleAssert(condition: () ->Bool, y: Bool, message: String) { if (y && !condition()) {//當爲False時,那麼整個式子的式子的值也爲False那麼在這種狀況下是不會調用condition的 println(message) } else { println("!= 42") } } func someExpensiveComputation() -> Int { return 41 } simpleAssert(false, {someExpensiveComputation() != 42},"==42")