Hi,
I’m very confused. I am trying to put together the ‘make an app with Swift’ fruit machine challenge. After a couple of false starts where I thought I understood functions etc but obviously don’t, I settled on a simplistic solution but there is a particular thing that doesn’t work and I can’t see any reason why not.
I have it set up so that when the spin button is pressed, each reel variable is assigned a random integer 1-3. Using if/else if/else statements, an apple/cherry/star is shown depending on the integer.
If all three reel variables are equal, you are told you are win, and given 1000 credits. However,
I get the following error:
Type ‘()’ cannot conform to ‘View’; only struct/enum/class types can conform to protocols
The particular code is here:
if reel1==reel2 && reel1==reel3 {
Text("You Win!")
credits += 1000
}
If I get rid of the 'credits += 1000 it will be okay and the Text will show when the three reels match, and in the war game app that was created during the course there’s multiple instances where ‘if’ is used to += update a variable. I might be going word blind but I can’t see how there is any difference between the fruit machine app and the war game app in how I have tried to implement this…
Thanks in advance for any help here, I can’t for the life of me understand why what I am doing won’t work!
Full code below:
struct ContentView: View {
//properties
@State var credits:Int = 1000
@State var reel1:Int = 1
@State var reel2:Int = 1
@State var reel3:Int = 1
var body: some View {
ZStack {
// Image("background")
// .scaledToFit()
VStack {
Text("🪙 SwiftUI Slots! 🪙")
.font(.largeTitle)
.fontWeight(.heavy)
.foregroundColor(Color.blue)
// Spacer()
//CREDIT DISPLAY
Text("Credits: \(credits)")
.fontWeight(.bold)
.padding(/*@START_MENU_TOKEN@*/.all, 6.0/*@END_MENU_TOKEN@*/)
.background(Color.white .cornerRadius(20) .opacity(0.5))
//CREDIT COUNTER
if reel1==reel2 && reel1==reel3 {
Text("You Win!")
credits += 1000
}
//Spacer()
//FRUIT SPINNER
//
HStack {
if reel1 == 1 {
Image("apple")
}
else if reel1 == 2 {
Image("cherry")
}
else {
Image("star")
}
//
if reel2 == 1 {
Image("apple")
}
else if reel2 == 2 {
Image("cherry")
}
else {
Image("star")
}
//
if reel3 == 1 {
Image("apple")
}
else if reel3 == 2 {
Image("cherry")
}
else {
Image("star")
}
}
// Spacer()
//SPIN BUTTON
Button(action: {
reel1 = Int.random(in: 1...3)
reel2 = Int.random(in: 1...3)
reel3 = Int.random(in: 1...3)
credits -= 100
}, label: {
Text("Spin!")
.fontWeight(.bold)
.padding(/*@START_MENU_TOKEN@*/.all/*@END_MENU_TOKEN@*/)
.background(Color.yellow .cornerRadius(36) .opacity(1))
})
// Spacer()
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}