【问题标题】:Can a struct have lazy properties [instantiation] in Swift?结构可以在 Swift 中具有惰性属性 [实例化] 吗?
【发布时间】:2016-09-20 22:55:26
【问题描述】:

结构体可以在 Swift 中具有惰性属性 [实例化] 吗?

我找不到任何说明是或否的文档。一切都只以类为例。

如果可以,是否可以在任何地方找到示例?

谢谢

斯坦

【问题讨论】:

    标签: swift struct lazy-initialization


    【解决方案1】:

    是的,结构可以具有惰性属性。考虑这个例子:

    class Stuff {
        var stuff: Int
    
        init(value: Int) {
            print("Stuff created with value \(value)")
            stuff = value
        }
    }
    
    struct HasLazy {
        lazy var object = Stuff(value: 1)
        var object2 = Stuff(value: 2)
    }
    
    func testIt() {
        print("in testIt")
    
        var haslazy = HasLazy()
    
        print("done")
        haslazy.object.stuff = 17
        print("\(haslazy.object.stuff)")
        print("final")
    }
    
    testIt()
    

    输出:

    in testIt
    Stuff created with value 2
    done
    Stuff created with value 1
    17
    final
    

    请注意,标记为lazy 的属性在首次访问该属性时打印"done" 之后才会初始化。

    查看here 的实际应用,然后尝试不使用lazy 关键字。

    【讨论】:

    • OK 完美就是我想要的。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-26
    • 1970-01-01
    • 1970-01-01
    • 2016-08-09
    • 2015-11-29
    相关资源
    最近更新 更多