swift - 不能在属性初始化器中使用实例成员“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' 可用之前运行”
我真的不明白发生了什么。非常感谢你的帮助!
解决方案
在调用之前 初始化属性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
....
}
推荐阅读
- java - Java错误:更新sql时索引超出范围
- git - 在 git 中取消跟踪 C 盘
- php - 在 crud 中进行更改更改后如何首先检查数据库中的用户状态
- c# - 创建用于将数据加载到 crm 的通用包
- flutter - gridview中项目之间的空间颤动
- laravel-5 - 如何部署由 Laravel 支持的 Vuejs 应用程序,以类似的方式,我们通常部署 laravel 应用程序,或者我需要单独的前端和后端实例?
- c# - 在 LINQ 中使用 '1,2,3,4,5'.Contains(ID int)?
- python - scipy UnivariateSpline 因多值 X 而失败
- python - 当我输入 import pygame 时,我收到一条错误消息:
- angular - 订阅 Observable 与订阅 Subject