问题
I would like to access to variables in other structs to have a total count.
Example code would demonstrate better:
struct level1: View {
@State var score1 = 5 
}
struct level2: View {
@State var score2 = 7 
}
In another struct, I would like to be able use score1 and score2 variables. The below code doesn't work, but I need something like this.
struct finalScore: View {
@State var totalScore = level1.score1 + level2.score2 
}
回答1:
Rethink it in some different way... like below, single-source trust, model separated - view separated, model changed - view react, this is the way SwiftUI goes.
Like
import SwiftUI
import Combine
class ScoreModel: ObservableObject {
    @Published var score1 = 5
    @Published var score2 = 7
}
struct MainView: View {
    @ObservedObject var vm: ScoreModel = ScoreModel()
    var body: some View {
        VStack {
            level1(vm: vm)
            level2(vm: vm)
            Divider()
            finalScore(vm: vm)
        }
    }
}
struct level1: View {
    @ObservedObject var vm: ScoreModel
    var body: some View {
        Text("\(vm.score1)")
    }
}
struct level2: View {
    @ObservedObject var vm: ScoreModel
    var body: some View {
        Text("\(vm.score2)")
    }
}
struct finalScore: View {
    @ObservedObject var vm: ScoreModel
    var body: some View {
        Text("\(vm.score1 + vm.score2)")
    }
}
回答2:
You would need to use @State & @Binding to accomplish this. Here's a working code that does what you are asking for.
import SwiftUI
struct ContentView: View {
    @State var score1: Int = 5
    @State var score2: Int = 7
    var body: some View {
        VStack {
            HStack {
                FirstView(score1: $score1)
                SecondView(score2: $score2)
                Spacer()
            }
            Divider()
            Text("The total score is \(score1 + score2)")
            Spacer()
        }
        .padding()
    }
}
struct FirstView: View {
    @Binding var score1: Int
    var body: some View {
        Stepper(value: $score1, in: 0...100) {
            Text("\(score1)")
        }
    }
}
struct SecondView: View {
    @Binding var score2: Int
    var body: some View {
        Stepper(value: $score2, in: 0...100) {
            Text("\(score2)")
        }
    }
}
来源:https://stackoverflow.com/questions/60639311/how-to-access-to-a-variable-in-another-struct-swiftui