[Swift] Overriding a stored property

最近在用 Swift 開發時,遇到一個問題,在父類別宣告了一個變數,子類別要覆寫變數時,發生了 Overriding a stored property 這個問題,後來終於試出解法了,分享給大家。

swift 1

先來看錯誤的程式碼 (Wrong Code):

class C: UIViewController {

}

class A: UIViewController  {

    lazy var viewControllers: [UIViewController] = [
    ]
}

class B: A  {
  override var viewControllers: [UIViewController]  = [C()]
}
/// Error, Cannot override with a stored property 'viewControllers'

那我們如何解決呢?很簡單,只要用 get、set 就好了! (Solution)

class C: UIViewController {

}

class A: UIViewController  {

    lazy var viewControllers: [UIViewController] = [
    ]
}

class B: A  {
    override var viewControllers: [UIViewController] {
      get {return [C()]}
      set {}
    }
}

另一個解決方法是用 func,再 override func,也是可以達到異曲同工之妙! (Alternative Solution)

class C: UIViewController {

}

class A: UIViewController  {

    lazy var viewControllers: [UIViewController] = getViewControllers()

    func getViewControllers() ->  [UIViewController]{
    }
}

class B: A  {
    override func getViewControllers() ->  [UIViewController]{
      return [C()]
    }
}

發表迴響