代码之家  ›  专栏  ›  技术社区  ›  Daniel Shin

Extension(Swift)中的延迟加载属性

  •  10
  • Daniel Shin  · 技术社区  · 11 年前

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

    是否有任何黑客/替代/忽略的方法来模拟扩展中的懒惰var?

    谢谢

    2 回复  |  直到 11 年前
        1
  •  13
  •   Aaron Brager    7 年前

    如果您不需要参考 self 您可以使用 static var :

    extension String {
        static var count = 0
        static var laughingOutLoud : String = {
            count++
    
            return "LOL: \(count)"
        }()
    }
    
    String.laughingOutLoud // outputs "LOL: 1"
    String.laughingOutLoud // outputs "LOL: 1"
    String.laughingOutLoud // outputs "LOL: 1"
    

    (你不需要 count 在您的实施中;这只是为了显示它只执行一次。)

        2
  •  5
  •   SolaWing    11 年前

    可以使用computed属性和associatedObject。通过这种方式,您可以模拟存储的属性。因此延迟var模拟将是:

    // 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))
        }
    }