扩展(Swift)中的延迟加载属性 [英] Lazy loading property in Extension (Swift)

查看:90
本文介绍了扩展(Swift)中的延迟加载属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道swift不允许在扩展中声明存储的属性.同样,也禁止延迟加载属性.我知道计算属性是一种替代方法,但是我执行的任务只能执行一次.

I know that swift doesn't allow declaring stored property within extension. And by the same token, lazily loaded properties are also prohibited. I know computed property is an alternative, but the task I have should only be executed once.

是否有任何破解/替代/被忽略的方式来模仿扩展中的惰性var?

Is there any hack/alternative/overlooked way to mimic lazy var in extension?

谢谢!

推荐答案

您可以使用与关联对象结合使用的计算属性.这样,您可以模仿存储的属性.所以惰性var模拟将是:

you can use computed property, combined with associatedObject. in this way, you can mimic a stored property. so the lazy var simulation will be:

// global var's address used as key
var #PropertyKey# : UInt8 = 0
var #varName# : #type# {
    get {
        if let v = objc_getAssociatedObject(self, & #PropertyKey#) as #type# {
            return v
        }else {
            // the val not exist, init it and set it. then return it

            // this way doesn't support nil option value. 
            // if you need nil option value, you need another associatedObject to indicate this situation.
        }
    }
    set {
        objc_setAssociatedObject(self, & #PropertyKey#, newValue, objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN_NONATOMIC))
    }
}

这篇关于扩展(Swift)中的延迟加载属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆