如何删除Swift数组中的所有nil元素? [英] How can I remove all nil elements in a Swift array?

查看:540
本文介绍了如何删除Swift数组中的所有nil元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本方式不起作用。

for index in 0 ..< list.count {
    if list[index] == nil {
        list.removeAtIndex(index) //this will cause array index out of range
    }
}


推荐答案

您的代码存在的问题是 0 ..< list.count 在循环开始时执行一次,当 list 仍然包含其所有元素时。每次删除一个元素时, list.count 都会递减,但迭代范围不会被修改。你最终阅读得太过分了。

The problem with your code is that 0 ..< list.count is executed once at the beginning of the loop, when list still has all of its elements. Each time you remove one element, list.count is decremented, but the iteration range is not modified. You end up reading too far.

在Swift 4.1及以上版本中,你可以使用 compactMap 丢弃 nil 元素序列。 compactMap 返回一组非可选值。

In Swift 4.1 and above, you can use compactMap to discard the nil elements of a sequence. compactMap returns an array of non-optional values.

let list: [Foo?] = ...
let nonNilElements = list.compactMap { $0 }

在Swift 2到4.0中,使用 flatMap flatMap 做同样的事情:

In Swift 2 to and including 4.0, use flatMap. flatMap does the same thing:

let list: [Foo?] = ...
let nonNilElements = list.flatMap { $0 }

如果你还想要一个选项数组,或者如果你仍在使用Swift 1,你可以使用 filter 来删除 nil 元素:

If you still want an array of optionals, or if you're still using Swift 1, you can use filter to remove nil elements:

list = list.filter { $0 != nil }

这篇关于如何删除Swift数组中的所有nil元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆