如何创建字典扩展

时间:2019-06-17 10:16:58

标签: swift dictionary

我有这段代码可以从Double中获得[String: Any]的金额,并格式化这样的字符串

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
    }
}

1 个答案:

答案 0 :(得分: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