Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Initializer 'init(_:)' requires that 'Binding<String>' conform to 'StringProtocol' SwiftUI Text

I am rewriting my app that randomises the numbers from the set for SwiftUI with Combine.

import SwiftUI
import Combine

private final class SomeViewState: ObservableObject {
        
        @Published var resultString = ""
        
    }
    
    struct SomeContent: View {
        
        @StateObject private var state = SomeViewState()
        
        func iterateAndRemove() -> (Set<Int>, Set<Int>){
            var numbers = Set<Int>(1...50)
            var results = Set<Int>()
            for _ in 1...3{
                let randomNumbers = numbers.randomElement()!
                results.insert(randomNumbers)
                numbers.remove(randomNumbers)
            }
        return (numbers, results)
        }
        
        var body: some View {
            VStack{
                Text("Some Text")
                    (...)
                
                Text($state.resultString)
                    .multilineTextAlignment(.center)
                    .frame(width: 195, height: 70)
                    .background(Rectangle().fill(Color.white).shadow(radius: 3))
                    .padding()
                
                Button("Randomise") {
                
                    let runFunction = iterateAndRemove()
                    theResult = runFunction.1
                    state.resultString = theResult.map(String.init).joined(separator: ", ")
                    
                }.padding()

As stated in the title I get the

Initializer 'init(_:)' requires that 'Binding<String>' conform to 'StringProtocol' SwiftUI Text

error. The only solutions I found in the Internet were for when the button throws such an error.
Please help!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Text displays an immutable String, hence it’s initialiser takes a String, not a Binding<String>.

So inject the String, not a Binding to it.

Text(state.resultString)

Moreover, @State should only be used on Views. resultString should be @Published, not @State.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading