Hey so I've just started using Xcode and I don't really know a lot about Swift. I followed an online tutorial on how to create a Tic Tac Toe App on IOS using SwiftUI. My Problem is the following: At some point, an error shows up that suggests I "try breaking up the expression into distinct sub-expressions"
Here's the part of my code where it shows up:
var body: some View {
VStack{
LazyVGrid(columns: Array(repeating:
GridItem(.flexible(), spacing: 15), count: 3), spacing: 15){
ForEach(0..<9,id: \.self){ index in
ZStack{
if moves [index] == "X"{
Color.orange
}
else {
Color.yellow
}
Color.white
.opacity(moves[index] == "" ? 1 : 0)
Text(moves[index])
.font(.system(size: 50))
.fontWeight(.heavy)
.foregroundColor(.white)
.opacity(moves[index] != "" ? 1 : 0)
}
.frame(width: getWidth(), height: 140)
.cornerRadius(18)
.rotation3DEffect(
.init(degrees: moves[index] != "" ? 180 : 0),
axis: (x: 0.0, y: 1.0, z: 0.0),
anchor: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/,
anchorZ: /*@START_MENU_TOKEN@*/0.0/*@END_MENU_TOKEN@*/,
perspective: 1.3
)
// Whenever tapped adding move...
.onTapGesture(perform: {
withAnimation(Animation.easeIn(duration: 0.5)){
if moves [index] == ""{
moves[index] = isPlaying ? "X" : "0"
isPlaying.toggle()
}}
})
}
}
.padding(15)
}
}
// Whenever moves updated it will check for winner...
.onChange(of: moves, perform: { value in
checkWinner()
})
.alert(isPresented: $gameOver, content:{
Alert(title: ("Winner"), message: Text(msg), dismissButton: .destructive(Text("Play Again"), action: {
//resetting all data...
withAnimation(Animation.easeIn(duration: 0.5)){
moves.removeAll()
moves = Array(repeating: "", count: 9)
isPlaying = true
}
}))
})
}
Your Alert
is incorrect. You're passing Strings rather than Texts. Also check your {} pairings; the one before .onChange
is unbalanced.
The way you debug this is to do as the error tells you to. Split up the View into smaller Views. Cmd-Shift-A, Exact Subview is very helpful for this. When the Views are smaller, the compiler has a better chance of providing a good error message. Splitting up a View into smaller sub-Views is good practice anyway. Views are extremely cheap in SwiftUI, and are intended to be relatively simple.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.