看来这个问题已经得到了很大的回答,但是回过头来看原始帖子,这是(IMHO)Swift中相对简洁的翻译。关键是您可以链接惰性属性。请注意,我同时使用了类函数和闭包-
两者都很好。
import Swiftprintln("begin")class ClassWithLazyProperties { lazy var entries:[String] = ClassWithLazyProperties.loadStuff() lazy var entriesByNumber:Dictionary<Int, String> = { var d = Dictionary<Int, String>() for i in 0..<self.entries.count { d[i] = self.entries[i] } return d }() private class func loadStuff() -> [String] { return ["Acai", "Apples", "Apricots", "Avocado", "Ackee", "Bananas", "Bilberries"] }}let c = ClassWithLazyProperties()c.entriesByNumber // 0: "Acai", 1: "Apples", 2: "Apricots", 3: "Avocado", 4: "Ackee", 5: "Bananas", 6: "Bilberries"]println("end")
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)