【问题标题】:Swift: More elegant way to write this array mapping?Swift:更优雅的方式来编写这个数组映射?
【发布时间】:2019-05-17 07:06:11
【问题描述】:

我想知道是否有更优雅的方式来写这个:

struct S {
    var state: [String: Any] 

    public var amounts: [Amount] {
        var result: [Amount] = []
        (self.state["amounts"] as? [Any]?)??.forEach({ a in
            result.append(Amount(a))
        })
        return result
    }      
}

struct Amount {
    init(_ any: Any?) {}
}

我已经尝试使用map 作为数组,但我找不到这样做的方法。

【问题讨论】:

  • amounts 的值很可能比[Any] 更具体
  • 由于 amounts 数组将根据来自 stateoptional 值填充,我建议将其声明为可选数组 ([Amount]?)。

标签: ios arrays swift xcode


【解决方案1】:

您也可以使用guard let 并提前返回,这样看起来会更好一些。

这是我的做法,

struct S {

    var state: [String: Any]

    public var amounts: [Amount] {
        guard let amounts = state["amounts"] as? [Any] else {
            return []
        }

        return amounts.map(Amount.init)
    }

}

【讨论】:

  • 我同意这一点。与其他答案相比,方法非常迅速且易于理解。
  • 你认为map(Amount.init) 会比.map { Amount($0) } 更具可读性吗?
  • 这取决于人与人。我会假设 OP 会知道基本的 swift 语法。对我来说 map(Amount.init) 肯定比完全封闭的更易读且更短。
【解决方案2】:
struct S {
    var state: [String: Any]
    public var amounts: [Amount] {
        return (self.state["amounts"] as? [Any] ?? []).map({ Amount($0) })
    }
}

struct Amount {
    init(_ any: Any?) {}
}

【讨论】:

  • 我收到一个错误:Cannot convert value of type 'Amount' to closure result type '[Amount]'
  • @Rob 将 return 替换为 return (self.state["amounts"] as? [Any] ?? []).map({ Amount($0) })
【解决方案3】:

您在这里使用了太多不必要的选项。您应该始终将as? 与非可选类型一起使用。而不是forEach,而是使用map

public var amounts: [Amount] {
    if let anyArray = self.state["amounts"] as? [Any] {
        return anyArray.map(Amount.init)
    } else {
        return []
    }
}

【讨论】:

    【解决方案4】:

    你可以在一行中完成它,

    public var amounts: [Amount] {
        return (self.state["amounts"] as? [Any])?.map({ Amount($0) }) ?? []
    }
    

    【讨论】:

      【解决方案5】:
      init(_ state: [Amount]) {
          self.init()
          guard let amounts = state["amounts"] as? [Any] else {
              return []
          }
      
          return amounts.map(Amount.init)
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-08-31
        • 1970-01-01
        • 2011-01-20
        • 2019-01-12
        • 1970-01-01
        • 1970-01-01
        • 2015-11-16
        相关资源
        最近更新 更多