Swift Instance member cannot be used on type

前端 未结 2 558
粉色の甜心
粉色の甜心 2020-12-16 15:21

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 {
          


        
相关标签:
2条回答
  • Problem is that you never initialized class anywhere so you cannot access the members of a non existing object (correct me if I'm wrong). Adding static will do the trick:

    class supClass: UIView {
        static let defaultFontSize: CGFloat = 12.0
    }
    
    0 讨论(0)
  • 2020-12-16 16:01

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

    0 讨论(0)
提交回复
热议问题