本文介绍了如何使用swift flatMap来过滤数组中的可选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对flatMap有点困惑(添加到Swift 1.2中)



假设我有一些可选类型的数组,例如

  let possibles:[Int?] = [nil,1,2,3,nil,nil,4,5] 

在Swift 1.1中,我会做一个过滤器,然后像这样的映射:

  let filtermap = possibles.filter({return $ 0!= nil})。map({return $ 0!})
// filtermap = [1,2,3,4,5]

我一直在试图用flatMap一些方法:

pre $ var flatmap1 = possibles.flatMap({
return $ 0 == nil?[]:[














  var flatmap2:[Int] = possibles.flatMap({
如果让exercise = $ 0 {return [exercise]}
return []
})

我更喜欢最后一种方法(因为我不必强制展开 $ 0! ...我害怕这些并且不惜一切代价避免它们),除了我需要指定Array类型。



是否有替代方案计算出t? ype通过上下文,但没有强制unwrap?

解决方案

使用Swift 2 b1,您可以简单地执行

  let possibles:[Int?] = [nil,1,2,3,nil,nil,4,5] 
let actuals = possibles.flatMap {$ 0}

对于早期版本,您可以使用以下扩展名:

 扩展数组{
func flatMap< U>(transform:Element - > U?) - > [U] {
var result = [U]()
result.reserveCapacity(self.count)
for map中的item(变换){
if let item = item {
result.append(item)
}
}
返回结果
}
}

一个警告(对于Swift 2也是如此)是您可能需要显式地键入转换的返回值:

  let actuals = [a,1]。flatMap {str  - >诠释?如果让int = str.toInt(){
返回int
} else {
返回nil
}
}
断言(
) actuals == [1])$ ​​b $ b

更多信息,请参阅


I'm a little confused around flatMap (added to Swift 1.2)

Say I have an array of some optional type e.g.

let possibles:[Int?] = [nil, 1, 2, 3, nil, nil, 4, 5]

In Swift 1.1 I'd do a filter followed by a map like this:

let filtermap = possibles.filter({ return $0 != nil }).map({ return $0! })
// filtermap = [1, 2, 3, 4, 5]

I've been trying to do this using flatMap a couple ways:

var flatmap1 = possibles.flatMap({
    return $0 == nil ? [] : [$0!]
})

and

var flatmap2:[Int] = possibles.flatMap({
    if let exercise = $0 { return [exercise] }
    return []
})

I prefer the last approach (because I don't have to do a forced unwrap $0!... I'm terrified for these and avoid them at all costs) except that I need to specify the Array type.

Is there an alternative away that figures out the type by context, but doesn't have the forced unwrap?

解决方案

With Swift 2 b1, you can simply do

let possibles:[Int?] = [nil, 1, 2, 3, nil, nil, 4, 5]
let actuals = possibles.flatMap { $0 }

For earlier versions, you can shim this with the following extension:

extension Array {
    func flatMap<U>(transform: Element -> U?) -> [U] {
        var result = [U]()
        result.reserveCapacity(self.count)
        for item in map(transform) {
            if let item = item {
                result.append(item)
            }
        }
        return result
    }
}

One caveat (which is also true for Swift 2) is that you might need to explicitly type the return value of the transform:

let actuals = ["a", "1"].flatMap { str -> Int? in
    if let int = str.toInt() {
        return int
    } else {
        return nil
    }
}
assert(actuals == [1])

For more info, see http://airspeedvelocity.net/2015/07/23/changes-to-the-swift-standard-library-in-2-0-betas-2-5/

这篇关于如何使用swift flatMap来过滤数组中的可选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 12:13