I am a beginner to Swift, SwiftUI, and using Xcode. I have been doing a couple of online tutorials and came across a problem when doing this bonus challenge.
import SwiftUI
struct ContentView: View {
@State var userCredits = 1000
@State var slot1 = 1
@State var slot2 = 1
@State var slot3 = 1
var body: some View {
VStack {
Text("SwiftUI Slot!")
.font(.system(size: 38))
.fontWeight(.medium)
Spacer()
Text("Credits: (userCredits)")
Spacer()
HStack{
Image("apple(slot1)")
.resizable()
.aspectRatio(contentMode: .fit)
Image("cherry(slot2)")
.resizable()
.aspectRatio(contentMode: .fit)
Image("star(slot3)")
.resizable()
.aspectRatio(contentMode: .fit)
}
Spacer()
Button("Spin") {
slot1 = Int.random(in: 1...3)
slot2 = Int.random(in: 1...3)
slot3 = Int.random(in: 1...3)
if slot1 == slot2 && slot2 == slot3{
userCredits += 15
}
else {
userCredits -= 5
}
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
The images of the apple, cherry, and star disappear when I put the (slot#) after it
I tried taking out the (slot#) but that will simply display the picture of the images and not change them nor make the game work as intended
2
Answers
What you need is to add your images into an array and then use the values for your
slot#
properties as indices for getting an image from the arraySo add an array property first to your view
Then change the call to
Image(...)
to use this arrayand so on for the other two
You could do this by declaring an array of image names:
then use something like:
Also, don’t forget that Swift arrays are zero based, so your spin function should be: