Lazy property initialization in Swift

后端 未结 9 1155
深忆病人
深忆病人 2020-12-18 04:25

How would you implement the following pattern in Swift?

The Container class is initialized with a JSON array that contains dictionaries. These dictionar

9条回答
  •  被撕碎了的回忆
    2020-12-18 04:52

    It seems that this question has largely been answered, but to circle back to the original post, here is (IMHO) a relatively succinct translation in Swift. The key is that you can chain lazy properties. Note that I used both a class function and a closure - either is fine.

    import Swift
    
    println("begin")
    
    class ClassWithLazyProperties {
    
        lazy var entries:[String] = ClassWithLazyProperties.loadStuff()
        lazy var entriesByNumber:Dictionary = {
    
            var d = Dictionary()
            for i in 0.. [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")
    

提交回复
热议问题