我对Swift很新,从未编写过Objective-C。
我正在尝试迭代2D数组quiz
(问题/答案)并将答案添加到另一个数组onlyAnswers
我尝试在for循环中使用for循环但遇到问题,我显然遗漏了一些东西......
为什么我不能在while循环中使用测验[j] [1]来附加到新数组? onlyAnswers.append(quiz[j][1]
或甚至作为简单数学let math = 1 + quiz[j][1]
的值?
var quiz = [
//Array of questions with their answers. question/answers
["2 + 1 ", 3],
["10 - 8", 2],
["4 x 2", 8],
["10 / 2", 5],
["7 + 2", 9]
]
var onlyAnswers: [Int] = []
var j = 0
while j < quiz.count{
// print answers
print(quiz[j][1]) // 3, 2, 8, 5, 9
// do something with quiz[j][1]
onlyAnswers.append(quiz[j][1])
// Error: Cannot convert value of type 'NSObject' tp expected argument type 'Int'
j += 1
}
如何实际执行此操作的任何代码示例都会很棒?
答案 0 :(得分:1)
struct
&{39}和tuples
将更适合此。
var onlyAnswers = [Int]()
var j = 0
while j < quiz.count{
print(quiz[j][1]) // 3, 2, 8, 5, 9
if let isInt = quiz[j][1] as? Int{
onlyAnswers.append(isInt)
}else{
print("Value \(quiz[j][1]) isn't of type Int , Thus cant be appended to an array of type [Int] ")
}
j += 1
}
答案 1 :(得分:1)
Swift是一种类型安全的语言,因此在编译时检查表达式的类型。
您的quiz
在Xcode的“快速帮助”面板中显示为[Array<Any>]
,这意味着quiz[j][0]
的类型为Any
。您已将onlyAnswers
声明为[Int]
,因此附加值需要包含Int
类型。
因此,明确地转换为Int
是解决问题的一种方法,另一种方法是更改数据结构。
使用元组类型,您可以为每个元素分配适当的类型。
var quiz: [(question: String, answer: Int)] = [
//Array of questions with their answers. question/answers
("2 + 1 ", 3),
("10 - 8", 2),
("4 x 2", 8),
("10 / 2", 5),
("7 + 2", 9)
]
(这在某些情况下会造成一点点困难,但这是另一个问题。)
有了这个,您可以将while循环编写为:
var onlyAnswers: [Int] = []
var j = 0
while j < quiz.count{
// print answers
print(quiz[j].answer) // 3, 2, 8, 5, 9
// do something with quiz[j].answer
onlyAnswers.append(quiz[j].answer)
j += 1
}
或更短:
var onlyAnswers: [Int] = []
for j in 0..<quiz.count {
// print answers
print(quiz[j].answer) // 3, 2, 8, 5, 9
// do something with quiz[j].answer
onlyAnswers.append(quiz[j].answer)
}
更短一些:
var onlyAnswers: [Int] = []
for qa in quiz {
// print answers
print(qa.answer) // 3, 2, 8, 5, 9
// do something with qa.answer
onlyAnswers.append(qa.answer)
}
答案 2 :(得分:0)
将该行更改为
onlyAnswers.append(quiz[j][1] as! Int)
因为您的测验数组是混合类型。类型字符串的一个元素和Int类型的其他元素。并且onlyAnswers严格类型为Int。所以要附加元素测验[j] [1],你需要显式解包它以输入Int。