'Error "No exact matches in call to initializer"

I am a beginner developer and I want to add my price variable which is a double next to the title variable in my view. When i try Text(price) is is giving me the error "No exact matches in call to initializer". Is this because I cannot use a double inside a Text?

import SwiftUI

struct TaskRow: View {
    var task: String
    var price: Double
    var completed: Bool
    
    var body: some View {
        HStack(spacing: 20) {
            Image(systemName: completed ?
                  "checkmark.circle" : "circle")
            Text(price)           "No exact matches in call to initializer"
            Text(task)
        }
    }
}

struct TaskRow_Previews: PreviewProvider {
    static var previews: some View {
        TaskRow(task: "Do laundry", price: 1.00, completed: true)
    }
}

Screenshot of issue:

enter image description here



Solution 1:[1]

The issue is Text takes in a String, so you just need to convert the Double to a String first. You can do this if you want to plan for locale or different currencies

import SwiftUI

struct TaskRow: View {
    var task: String
    var price: Double
    var completed: Bool

    var priceString: String {
        return price.toLocalCurrency()
    }
    
    var body: some View {
        HStack(spacing: 20) {
            Image(systemName: completed ?
                  "checkmark.circle" : "circle")
            Text(priceString)
            Text(task)
        }
    }
}

struct TaskRow_Previews: PreviewProvider {
    static var previews: some View {
        TaskRow(task: "Do laundry", price: 1.00, completed: true)
    }
}

// This could be in another file
// Extension to convert doubles to currency strings consistently
extension Double {
    func toLocalCurrency() -> String {
        let formatter = NumberFormatter()
        var priceString = self.description
        formatter.locale = Locale.current
        formatter.numberStyle = .currency
        if let formattedTipAmount = formatter.string(from: NSNumber(value: self)) {
            priceString = formattedTipAmount
        }
        return priceString
    }
}

You could also use any of these if you don't want to bother with Locale for now:

  • Text("\(price)" // 1.00
  • Text(price.description) // 1.00
  • Text("$\(price)") // $1.00

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 TJ Olsen