2016-08-03 43 views
4

使用我定義的超類的變量,並試圖引用它的子類,但得到的實例成員的錯誤不能在類型斯威夫特實例成員不能在類型

class supClass: UIView { 
    let defaultFontSize: CGFloat = 12.0 
} 

class subClass: supClass { 

    private func calcSomething(font: UIFont = UIFont.systemFontOfSize(defaultFontSize)) { 
     //... Do something 
    } 
} 

使用這有什麼錯呢?非常感謝你

回答

3

的方法參數的默認值是在類範圍, 不是實例範圍評價,如一個可以在下面的例子中看到:

class MyClass { 

    static var foo = "static foo" 
    var foo = "instance foo" 

    func calcSomething(x: String = foo) { 
     print("x =", x) 
    } 
} 

let obj = MyClass() 
obj.calcSomething() // x = static foo 

和它沒有static var foo就不能編譯。

應用到你的情況下,它意味着你必須做出這是用來 作爲默認值的靜態屬性:

class supClass: UIView { 
    static let defaultFontSize: CGFloat = 12.0 // <--- add `static` here 
} 

class subClass: supClass { 

    private func calcSomething(font: UIFont = UIFont.systemFontOfSize(defaultFontSize)) { 
     //... Do something 
    } 
} 

(請注意,這是無關緊要這個問題的性質是否在規定 同級或超級。)

+0

非常感謝你馬丁R – Kevin

2

問題是,你永遠不會初始化類的任意位置,所以你不能訪問不存在的對象的成員(糾正我,如果我錯了)。添加static將這樣的伎倆:

class supClass: UIView { 
    static let defaultFontSize: CGFloat = 12.0 
} 
+0

非常感謝你阿明 – Kevin