【问题标题】:Map with Optional Unwrapping in Swift在 Swift 中使用可选展开的映射
【发布时间】:2015-06-30 21:15:22
【问题描述】:

假设我有以下 api:

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

我在需要[String] 的方法中使用它,因此我必须使用简单的map 函数解开它。我目前正在做:

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

这里,强制施法会导致错误。所以从技术上讲,我需要解开 paths 数组中的字符串。我在执行此操作时遇到了一些麻烦,并且似乎遇到了一些愚蠢的错误。有人可以帮我吗?

【问题讨论】:

    标签: swift dictionary optional unwrap


    【解决方案1】:

    compactMap() 可以为您一步到位:

    let paths:[String?] = ["test", nil, "Two"]
    
    let nonOptionals = paths.compactMap{$0}
    

    nonOptionals 现在将是一个包含["test", "Two"] 的字符串数组。

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

    【讨论】:

    • 感谢您从 Swift 未记录的高阶函数中挖掘出这个函数!
    • @ZoffDino - 这应该归功于 Airspeed Velocity:airspeedvelocity.net/2015/06/23/…,他首先向我指出了这一点。
    • 我已经使用 Swift 9 个月了,但仍然找不到该语言中高阶函数的完整列表。苹果在这方面有很多需要追赶的地方。
    • 注意:这适用于 Swift 2。对于 1.2,请使用 return paths.filter({$0 != nil}).map({$0 as String!})
    【解决方案2】:

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

    return paths.filter { $0 != .None }.map { $0 as! String }
    

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

    【讨论】:

      【解决方案3】:

      也许您想要的是 filter 后跟 map

      func cleanPaths() -> [String] {
          return paths()
                  .filter {$0 != nil}
                  .map {$0 as String!}
      }
      
      let x = cleanPaths()
      println(x) // ["test", "two"]
      

      【讨论】:

        【解决方案4】:
        let name = obj.value
        name.map { name  in print(name)}
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-03-20
          • 1970-01-01
          • 2022-01-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多