以下结果导致Swift 4 Playgrounds中出现“致命错误:索引超出范围”。我对Swift非常陌生;答案不应该是“ 10”吗?谢谢!
struct Example {
var partOne: Int
var partTwo: Int
var partThree: Int
}
var one = Example(partOne: 10, partTwo: 11, partThree: 12)
var two = Example(partOne: 10, partTwo: 11, partThree: 12)
var arrayOfExamples = [Example]()
print(arrayOfExamples[0].partOne)
答案 0 :(得分:3)
尝试下面的代码
struct Example {
var partOne: Int
var partTwo: Int
var partThree: Int
}
var one = Example(partOne: 10, partTwo: 11, partThree: 12)
var two = Example(partOne: 10, partTwo: 11, partThree: 12)
var arrayOfExamples = [one, two]
print(arrayOfExamples[0].partOne) // 10
print(arrayOfExamples[1].partOne) // 10
输出:10、10
使用转入循环
for i in arrayOfExamples {
print(i.partOne)
}
输出:10、10