Home > Enterprise >  How to display a random item in a list
How to display a random item in a list

Time:12-26

I want when the app is launched it shows a random question in my list and I only know how to show all my questions. Please can anyone help?

This is my view

import SwiftUI

struct ViewJouer2: View {
    @EnvironmentObject var data : DefisList
    var body: some View {
        List {
            
            ForEach(data.defis) { Defi in
                DefiRow(Defi: Defi)
            }
        }
    }
}

struct ViewJouer2_Previews: PreviewProvider {
    static var previews: some View {
        ViewJouer2()
            .environmentObject(DefisList())
    }
}

This is my Data

import SwiftUI

class DefisList : ObservableObject {
    @Published var defis = [
        Defi(question: "How old are you?"),
        Defi(question: "How are you"),
        Defi(question: "What is your name?"),
    ]
}
struct Defi : Identifiable {
    var question : String
    
    var id = UUID()
}

CodePudding user response:

If I understood your question correctly, you can use randomElement method to randomize the item you want to show. For example, your code can look like next:

import SwiftUI

struct ViewJouer2: View {
    @EnvironmentObject var data : DefisList
    var body: some View {
        List {
            if (!data.defis.isEmpty) {
                DefiRow(Defi: data.defis.randomElement()!)
            }
        }
    }
}

As an alternative you can use Int.random:

import SwiftUI

struct ViewJouer2: View {
    @EnvironmentObject var data : DefisList
    var body: some View {
        List {
            if (!data.defis.isEmpty) {
                DefiRow(Defi: data.defis[Int.random(in: 0..<data.defis.count)])
            }
        }
    }
}
  • Related