在 Swift 中使用可选展开的地图

Map with Optional Unwrapping in Swift

假设我有以下 api :

func paths() -> [String?] {
    return ["test", nil, "Two"]
}

我在需要 [String] 的方法中使用了它,因此我不得不使用简单的 map 函数将其解包。我目前正在做:

func cleanPaths() -> [String] {
    return paths.map({[=12=] as! String})
}

这里强制转换会报错。所以从技术上讲,我需要解开 paths 数组中的字符串。我在做这件事时遇到了一些麻烦,而且似乎遇到了一些愚蠢的错误。有人可以帮我吗?

也许您想要的是 filter 后跟 map:

func cleanPaths() -> [String] {
    return paths()
            .filter {[=10=] != nil}
            .map {[=10=] as String!}
}

let x = cleanPaths()
println(x) // ["test", "two"]

compactMap() 可以一步为您完成:

let paths:[String?] = ["test", nil, "Two"]

let nonOptionals = paths.compactMap{[=10=]}

nonOptionals 现在将是一个包含 ["test", "Two"].

的字符串数组

以前 flatMap() 是正确的解决方案,但在 Swift 4.1

中已为此目的弃用

您应该先过滤,然后映射:

return paths.filter { [=10=] != .None }.map { [=10=] as! String }

但是按照@BradLarson 的建议使用 flatMap 会更好

let name = obj.value
name.map { name  in print(name)}