【问题标题】:How to create Dictionary extension [duplicate]如何创建字典扩展[重复]
【发布时间】:2019-06-17 10:16:58
【问题描述】:

我有这段代码可以从[String: Any] 中获取Double 数量并格式化这样的字符串

if let amount = details["amount"] as? Double
{
    self.amountLbl.text = String(format: "%.2f", amount)
}

我正在尝试为此创建扩展

预期

//self.amountLbl.text = details.getInAmountFormat(str: "amount")

我的尝试

extension Dictionary where Key: StringProtocol {
    func getInAmountFormat(str: String) -> String? {
        if let value = self[str] as? Double {//Cannot subscript a value of type 'Dictionary<Key, Value>' with an index of type 'String'
            return String(format: "%.2f", value)
        }
        return nil
    }
}

【问题讨论】:

    标签: swift dictionary


    【解决方案1】:

    你差不多完成了,只需对 Key 类型进行正确的约束:

    extension Dictionary where Key == String {
        func getInAmountFormat(str: String) -> String? {
            if let value = self[str] as? Double {
                return String(format: "%.2f", value)
            }
            return nil
        }
    }
    

    另外,这里有一个有用的answer

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-03-27
      • 2021-02-21
      • 2016-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-09
      相关资源
      最近更新 更多