使用Swift中的可选解包映射

gra*_*aci 15 dictionary optional swift unwrap

说我有以下api:

func paths() -> [String?] {
    return ["test", nil, "Two"]
}
Run Code Online (Sandbox Code Playgroud)

我在我需要的方法中使用它[String],因此我不得不使用简单的map函数解开它.我现在正在做:

func cleanPaths() -> [String] {
    return paths.map({$0 as! String})
}
Run Code Online (Sandbox Code Playgroud)

强制转换会导致错误.所以从技术上讲,我需要在paths数组中打开字符串.我在做这件事时遇到了一些麻烦,似乎变得很愚蠢.有人可以帮帮我吗?

Bra*_*son 40

compactMap() 可以一步完成这件事:

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

let nonOptionals = paths.compactMap{$0}
Run Code Online (Sandbox Code Playgroud)

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

以前flatMap()是正确的解决方案,但在Swift 4.1中已被弃用


Ant*_*nio 5

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

return paths.filter { $0 != .None }.map { $0 as! String }
Run Code Online (Sandbox Code Playgroud)

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