我有一个[UIImageView?]数组,想迭代所有非零值。以下是我尝试过的事情:
// Kind of work:
for imageView in imageViews where imageView != nil { // works, but still have to use imageView! rather than imageView
for tmp in imageViews { guard let imageView = tmp else { continue } // works but feels wrong, looks weird/confusing, and neems unnecessarily longwinded
// Don't work: (in no particular order)
for x in imageViews, let imageView = x {
for let imageView in imageViews {
for (imageView in imageViews) as? UIImageView {
for imageView in imageViews as? UIImageView {
for imageView? in imageViews {
for imageView in imageViews ?? false {
for imageView in? imageViews {
for x in imageViews where let imageView = x {
答案 0 :(得分:7)
for case let .Some(x) in imageViews {
...
}
甚至没有循环:
let result = imageViews.flatMap { x in ... }
你甚至可以在flatMap结果上使用普通循环:
for imageView in imageViews.flatMap({$0}) {
}
答案 1 :(得分:2)
您正在寻找flatMap
,它可以消除nils并解开剩余的Optionals。简单的测试示例:
let arr : [UIImageView?] = [nil, UIImageView(), nil, UIImageView()]
let arr2 = arr.flatMap{$0} // eliminates the nils, unwraps the optionals
for iv in arr2 {
...
}
在此基础上,我实际写的是什么:
let arr : [UIImageView?] = [nil, UIImageView(), nil, UIImageView()]
arr.flatMap{$0}.forEach {iv in
print(iv) // or whatever
}
你会发现forEach
往往比for...in
更受欢迎,而这种链式情况就是一个很好的例子。