Swift
-
计算型属性(computed property)
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_closure
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")