Home > front end >  I want to create a loop that creates 10 different strings and use that strings to show 10 different
I want to create a loop that creates 10 different strings and use that strings to show 10 different

Time:10-29

import Foundation

class Card: Identifiable, ObservableObject {

var id = UUID()
var result: String = ""

init() {

for _ in 1...10 {

let suit = ["D","K","B","S"][Int(arc4random() % 4]
let numStr = ["1","2","3","4"][Int(arc4random() % 4]

result = suit   numStr
     }
   }
}



import SwiftUI

struct EasyModeView: View {

@ObservedObject var cardModel: Card

var body : some View {

HStack {

ForEach((1...10, id: \.self) { _ in 

Button { } label: { Image(cardModel.result) } } }

   }
}

I created loop but it always shows me 10 same cards and i want all 10 different. My Images in Assets are named same as combination of two variables example "D1","D2","S1","S2" etc.

CodePudding user response:

You are using only one card, instead of creating 10. Fix like this

struct EasyModeView: View {
    
    var body : some View {
        HStack {
            ForEach(0..<10) { _ in
                Button { } label: {
                    Image(Card().result)
                }
            }
        }
    }
}

CodePudding user response:

Here is a right way of what you are trying:

struct ContentView: View {
    
    var body: some View {
        
        EasyModeView()
        
    }
    
}

struct EasyModeView: View {
    
    @StateObject var cardModel: Card = Card()
    
    var body : some View {
        
        HStack {
            
            ForEach(cardModel.results) { card in

                Button(action: {}, label: {
                    
                        Text(card.result)
                            .padding(3.0)
                            .background(Color.yellow.cornerRadius(3.0))
                    
                })
                
            }
            
        }
        
        Button("re-set") { cardModel.reset() }.padding()

    }
}

struct CardType: Identifiable {

    let id: UUID = UUID()
    var result: String
}

class Card: ObservableObject {
    
   @Published var results: [CardType] = [CardType]()
    
    private let suit: [String] = ["D","K","B","S"]
    
    init() { initializing() }
    
    private func initializing() {
        
        if (results.count > 0) { results.removeAll() }
        
        for _ in 0...9 { results.append(CardType(result: suit.randomElement()!   String(describing: Int.random(in: 1...4)))) }
        
    }
    
    func reset() { initializing() }
    
}

Result:

enter image description here

  • Related