Swift Instance element cannot be used by type

I defined a variable in a superclass and tried to pass it to a subclass, but getting an error in an instance instance cannot be used for type

class supClass: UIView { let defaultFontSize: CGFloat = 12.0 } class subClass: supClass { private func calcSomething(font: UIFont = UIFont.systemFontOfSize(defaultFontSize)) { //... Do something } } 

What about him? thank you very much

+5
source share
2 answers

The default value of the method parameter is evaluated in the class area, not the instance area, as can be seen 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 won’t compile without static var foo .

For your case, this means that you must use the property, which is used as the default value of 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 for this problem it does not matter if the property is defined in the same class or superclass.)

+3
source

The problem is that you never initialized the class anywhere so that you cannot access members of a non-existing object (correct me if I am wrong). Adding static will do the trick:

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

All Articles