我创建了一个对象数组但是在初始化数组时我收到了这个神经紧张的错误。
import Foundation
import UIKit
class question{
var image = UIImage()
var q1: String = "a"
var q2: String = "b"
var q3: String = "c"
var q4: String = "d"
var q = ["a","b","c","d"]
static let shared = question()
}
let quest: [question] = []
func set(){
quest[0].image = #imageLiteral(resourceName: "Screen Shot 2017-05-15 at 4.14.27 PM.png")
quest[0].q[0] = "Mount"
quest[0].q[1] = "Sun"
quest[0].q[2] = "Ground"
quest[0].q[3] = "Tree"
quest[1].image = #imageLiteral(resourceName: "Screen Shot 2017-05-15 at 4.15.32 PM.png")
quest[1].q[0] = "cloud"
quest[1].q[1] = "lake"
quest[1].q[2] = "rain"
quest[1].q[3] = "snow"
}
这是我的模型文件,而不是viewController文件。 func“set()”在viewDidLoad的覆盖中的ViewController文件中执行。 EXC_BAD_INSTRUCTION只是在第一次初始化任务[0] .image时发生,但我在它之前添加//,错误移到下一行。
答案 0 :(得分:1)
数组quest
不包含任何元素,您无法通过quest[0]
访问它。
首先,让任务数组可以改变:
var quest: [question] = []
然后添加如下元素:
let question = question()
question.image = #imageLiteral(resourceName: "Screen Shot 2017-05-15 at 4.14.27 PM.png")
question.q[0] = "Mount"
question.q[1] = "Sun"
question.q[2] = "Ground"
question.q[3] = "Tree"
quest.append(question)
答案 1 :(得分:1)
像这样修改你的设置函数:
func set(){
var tempQuest1 = question()
quest.append(tempQuest1)
var tempQuest2 = question()
quest.append(tempQuest2)
quest[0].image = #imageLiteral(resourceName: "Screen Shot 2017-05-15 at 4.14.27 PM.png")
quest[0].q[0] = "Mount"
quest[0].q[1] = "Sun"
quest[0].q[2] = "Ground"
quest[0].q[3] = "Tree"
quest[1].image = #imageLiteral(resourceName: "Screen Shot 2017-05-15 at 4.15.32 PM.png")
quest[1].q[0] = "cloud"
quest[1].q[1] = "lake"
quest[1].q[2] = "rain"
quest[1].q[3] = "snow"
}
您需要纠正一些事项:
1)将question
类重命名为Question
,swift中的所有类(任何类型)都应为大写。
2)有必要让question
课成为单身人士吗?