参考链接:http://www.jianshu.com/p/eb718439551f
1 defer语法
defer是Swift2.0中加入的新语法声明。defer译为延缓、推迟之意。
defer的语法如下:
defer { //do something }
{}中添加延迟处理的代码。
当代码执行到defer语句时,它并不会立刻执行,而是放入defer栈中,当一个作用域结束后,该作用域中的语句会自上而下的调用栈中的语句。
2 代码示例
func lookforSomething(name:String) throws{ //这里是作用域1 整个函数作用域 print("1-1") if name == ""{ //这里是作用域2 if的作用域 print("2-1") defer{ print("2-2") } print("2-3") } print("1-2") defer{ print("1-3") } print("1-4") if name == "hello"{ //作用域3 print("3-1") defer{ print("3-2") } print("3-3") defer{ print("3-4") } } }
try! lookforSomething("")输出结果为: 1-1 2-1 2-3 2-2 1-2 1-4 1-3
try! lookforSomething("hello")输出结果为:
1-1
1-2
1-4
3-1
3-3
3-4
3-2
1-3
3 应用
public class MyNewType : NSObject { public var myOptionalField:Float? { willSet { if let newValue = newValue { print("I‘m going to change to \(newValue)") } } didSet { if let myOptionalField = self.myOptionalField { print("Now I‘m \(myOptionalField)") } } } override public init() { super.init() // Non-defered self.myOptionalField = 6.28 // Defered defer { self.myOptionalField = 3.14 } } }
输出结果为:
I‘m going to change to 3.14 Now I‘m 3.14
时间: 2024-10-10 07:18:44