0

I have this code to get a Double amount from a [String: Any] and format a string like this

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

Im trying to create an extension for this

Expected

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

My attempt

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
    }
}
arun siva
  • 809
  • 1
  • 7
  • 18

1 Answers1

1

You're almost done, just make right constraint on the Key type:

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

Also, here is an useful answer.

pacification
  • 5,838
  • 4
  • 29
  • 51