我有一个满是nil的空数组,我将填充满是int的数组,并希望看到它何时不再包含nil值。
我需要这个检查,看看是否有零,所以我可以添加ints,如果有,如果没有零值,那么停止游戏。
var smallestArr = [Int?](count: 25, repeatedValue: nil)
if smallestArr.contains(nil){
//add ints until it doesn't contain anymore nil
}else{
//end game
}发布于 2015-12-23 02:58:54
而不是
if smallestArr.contains(nil) {把这个:
if smallestArr.contains{$0 == nil} {Swift 4:
if smallestArr.contains(where: {$0 == nil}) {另一种方式是:
if smallestArr.flatMap{$0}.count == smallestArr.count {发布于 2015-12-23 03:10:52
你可以试试这样的方法:
var smallestArr = [Int?](count: 25, repeatedValue: nil)
var updatedArr = smallestArr.map { (val) -> Int in
if(val == nil){
//change this value to the int that you want to replace nil with
return -1;
}
else{
return val!;
}
}updatedArr将有一个数组,其中所有"nil“都替换为"-1”,所有其他值都保持不变。
给出了这个答案后,我更希望您应该以以下方式初始化您的数组:
var smallestArr = [Int?](count: 25, repeatedValue: -1)因此,您将完全避免零,并防止进入致命错误状态!!
发布于 2015-12-23 02:54:25
Array类型不是堆栈。它不是固定的长度,所以如果您试图用有效的Int值递增地替换nil,并期望最终将所有的nils推开,那么您就错了。尽管这不是您的问题,但考虑到您的代码示例,这似乎是隐含的理解。
[](repeatedValue:count:)是一种方便的方法,它多次初始化具有相同值的数组。这就像进行数组和一系列append方法调用一样,它没有赋予数组特殊的功能,FIFO或其他功能。
https://stackoverflow.com/questions/34427759
复制相似问题