只需替换map()
为flatMap()
:
extension SequenceType {
/// Returns an `Array` containing the non-nil results of mapping
/// `transform` over `self`.
///
/// - Complexity: O(*M* + *N*), where *M* is the length of `self`
/// and *N* is the length of the result.
@warn_unused_result
public func flatMap<T>(@noescape transform: (Self.Generator.Element) throws -> T?) rethrows -> [T]
}
try? ...
nil
如果调用抛出错误则返回,因此结果中将省略这些元素。
仅用于演示目的的独立示例:
enum MyError : ErrorType {
case DivisionByZeroError
}
func inverse(x : Double) throws -> Double {
guard x != 0 else {
throw MyError.DivisionByZeroError
}
return 1.0/x
}
let values = [ 1.0, 2.0, 0.0, 4.0 ]
let result = values.flatMap {
try? inverse($0)
}
print(result) // [1.0, 0.5, 0.25]
对于Swift 3,替换ErrorType
为Error
.
对于Swift 4使用compactMap