我有这段代码可以从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
}
}
答案 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。