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!
CodePudding user response:
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.
