我有一个IBAction,需要从变量中读取。但是,将变量放在viewDidLoad
之外时,会收到错误消息
无法在属性初始化程序中使用实例成员“ animal”;属性初始化程序在“自我”可用之前运行
我的代码如下。当我将变量移回viewDidLoad
内部时,错误指出未声明animalName
var animalName = (String(format: "%03d", animal.speciesId!))
@IBAction func megaKeyIBO(_ sender: Any) {
animalName = (String(format: "%03d", animal.speciesId!)) + "-merg"
}
override func viewDidLoad() {
super.viewDidLoad()
//variable was originally here before moving to top
var animalName = (String(format: "%03d", animal.speciesId!))
}
最佳答案
发生这种情况是因为您试图在属性animal.speciesId之前初始化animalName!已初始化。一种简单的解决方法是:
var animalName: String!
@IBAction func megaKeyIBO(_ sender: Any) {
animalName = (String(format: "%03d", animal.speciesId!)) + "-merg"
}
override func viewDidLoad() {
super.viewDidLoad()
// Initialize on viewDidLoad
animalName = (String(format: "%03d", animal.speciesId!))
}
关于ios - 错误?在IBAction按钮内读取变量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41433042/