I defined a variable in super class and trying to refer it in subclass but getting error on Instance member cannot be used on type
class supClass: UIView {
let defaultFontSize: CGFloat = 12.0
}
class subClass: supClass {
private func calcSomething(font: UIFont = UIFont.systemFontOfSize(defaultFontSize)) {
//... Do something
}
}
What's wrong with it? thank you so much
The default value of a method parameter is evaluated on class scope, not instance scope, as one can see in the following example:
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
and it would not compile without the static var foo
.
Applied to your case it means that you have to make the property which is used as the default value static:
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
}
}
(Note that it is irrelevant for this problem whether the property is defined in the same class or in a super class.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With