No exact matches in call to initializer of Text, how can I solve this issue in SwiftUI?

Viewed 2770

I am new to swift, this might be a stupid question but it confuses me a long time. Here is my code, I wrote this code by imitating the sandwich example from WWDC 2020's intro to swiftUI.

import SwiftUI

struct movieDetail: View {

    var idnum:Int

    var body: some View {

        Text(idnum)

    }
}

struct movieDetail_Previews: PreviewProvider {

    static var previews: some View {

        NavigationView {
            movieDetail(idnum:24428)
        }
       
    }
}

while it displays as compile error:

No exact matches in call to initializer.

WWDC 2020's example is below

import SwiftUI

struct sandwichdetail: View {

    var sandwich:Sandwich
    @State private var zoomed = false

    var body: some View {

        VStack {
            Text(sandwich.name)
        }
        .navigationTitle(sandwich.name)
        .edgesIgnoringSafeArea(.bottom)
    }
}

struct sandwichdetail_Previews: PreviewProvider {

    static var previews: some View {
        NavigationView{
            sandwichdetail(sandwich: testData[1])
        }
        
    }
}

I don't quite understand the difference between these 2 pieces of code and why mine fail and the sandwich example succeed displaying the sandwich's name.

3 Answers

The Text type doesn't have an initializer that takes an Int. Try this instead:

Text("\(idnum)")

Another more Swifty way, is using description because Int conforms to CustomStringConvertible protocol.

Text(idnum.description)

You can create your own initialiser for Text if this a common use case for you, using Swift's string interpolation. This may reduce type visibility at the call-site however.

extension Text {

    init(_ int: Int) {
        self = Text("\(int)")
    }

}
Related