iOS-延时加载,延时初始化
- OC版
-
// classA.h @property (nonatomic, copy) NSString *testString; //classA.m - (NSString*)testString { if (!_testString) { _testString = @"Hello"; NSLog(@"Print at first time"); } return _testString }
- Swift版
-
//在变量属性前加 lazy 指定延时加载 class ClassA { lazy var str: String = { let str = "Hello" print("print at first time") return str }() // or // lazy var str: String = "Hello" } // lazy + array.map / filter let data = 1...3 let result = data.lazy.map { (i: Int) -> Int in print("i is \(i)") return i * 2 } print("print results") for i in result { print("result is \(i)") } print("end") /* print results i is 1 result is 2 i is 2 result is 4 i is 3 result is 6 end */