我想从一个数组中获取值,并使用递归函数将它们放入另一个数组中。并且要注意我不想使用循环(如'for in loop')
var rudics = ["one", "two", "three", "four", "five", "six"]
var array = [""]
func changeArray (var new:[String]) {
array = [new.first!]
if new.count > 0 {
new.removeLast()
changeArray(new)
}
}
changeArray(rudics)
它给了我一个错误
fatal error: unexpectedly found nil while unwrapping an Optional value
Playground execution failed: Execution was interrupted, reason: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0).
依旧......
请帮助我!
答案 0 :(得分:2)
你可能会考虑这样的事情:
var rudics = ["one", "two", "three", "four", "five", "six"]
var array = [String]()
func changeArray (var new:[String]) {
if let first = new.first {
array.append(first)
new.removeAtIndex(0)
changeArray(new)
}
}
changeArray(rudics)