Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift Instance member cannot be used on type

Tags:

swift

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

like image 266
Kevin Avatar asked Aug 03 '16 08:08

Kevin


1 Answers

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.)

like image 154
Martin R Avatar answered Sep 27 '22 19:09

Martin R