Lazy property initialization in Swift

后端 未结 9 1162
深忆病人
深忆病人 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:47

    You could use an optional as the instance variable. Then create a function that returns the optional if it exists, and a new object if it does not to simulate lazy loading.

    class Lazy {
        var lazyVariable:String?
    
        func lazilyGetEntries() -> String {
            if let possibleVariable = self.lazyVariable { // optional already exists
                return possibleVariable
            }
            else {                                        // optional does not exist, create it
                self.lazyVariable = String()
                return self.lazyVariable!
            }
        }
    }
    

提交回复
热议问题