首页 > 解决方案 > 不能在属性初始化器中使用实例成员“currColor”;属性初始化程序在“自我”可用之前运行

问题描述

所以我对 Swift 很陌生,希望能在这次大流行期间迅速自学。我正在制作一个应用程序,它所做的只是在按下按钮时更改标签的颜色。我的故事板看起来像这样

    @IBAction func ChangeButton(_ sender: Any) {
        TopLeft.backgroundColor = CornerColor(c: TopLeft.backgroundColor!).getFirstColor()
    }

我的 CornerColor 类看起来像这样

    class CornerColor{

        var currColor : UIColor

        init(c : UIColor) {
            self.currColor = c
        }
        private static let colorsArray = [UIColor.black, UIColor.red, UIColor.yellow, UIColor.blue]

        var index = colorsArray.firstIndex(of: currColor)
        ....
    }

我希望从 index 中,当 TopLeft.backgroundColor 传递给 CornerColor 类时,它将读取颜色并查看数组中的哪个位置是颜色,然后执行 index++ 以获得下一个颜色。

但是,在“var index”行中,它显示“不能在属性初始化程序中使用实例成员 'currColor';属性初始化程序在 'self' 可用之前运行”

我真的不明白发生了什么。非常感谢你的帮助!

标签: swiftxcodemacos

解决方案


在调用之前 初始化属性init()(代码中的顺序无关紧要,以防万一),这就是错误的原因。这是更正的变体

class CornerColor{

        var currColor : UIColor

        init(c : UIColor) {
            self.currColor = c
            self.index = colorsArray.firstIndex(of: c)
        }
        private static let colorsArray = [UIColor.black, UIColor.red, UIColor.yellow, UIColor.blue]

        var index: Int 
        ....
    }

推荐阅读