加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Swift Instance成员不能用于类型

发布时间:2020-12-14 05:31:18 所属栏目:百科 来源:网络整理
导读:我在超类中定义了一个变量并尝试在子类中引用它,但是在实例成员上获取错误不能在类型上使用 class supClass: UIView { let defaultFontSize: CGFloat = 12.0}class subClass: supClass { private func calcSomething(font: UIFont = UIFont.systemFontOfSize
我在超类中定义了一个变量并尝试在子类中引用它,但是在实例成员上获取错误不能在类型上使用
class supClass: UIView {
    let defaultFontSize: CGFloat = 12.0
}

class subClass: supClass {

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

它出什么问题了?非常感谢

在类范围上计算方法参数的默认值,
不是实例范围,如下例所示:
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

如果没有静态var foo,它就不会编译.

适用于您的情况,这意味着您必须使用所使用的属性
作为默认值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
    }
}

(请注意,无论是否在中定义了属性,都与此问题无关同一个班级或超级班.)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读