Home > OS >  Picking a random element from Swift Class
Picking a random element from Swift Class

Time:12-23

This is a model of my makeshift database

    var categories: [Category] = [

            Category(name: "X",
                     sign: [Sign(code: "X-1", name: "***", description: "", picture: ""),
                            Sign(code: "X-2", name: "***", description: "", picture: "")]),
            Category(name: "Y",
                     sign: [Sign(code: "Y-1", name: "Yyy", description: "", picture: ""),
                            Sign(code: "Y-2", name: "yyy", description: "", picture: "")]),
            Category(name: "Z",
                     sign: [Sign(code: "Z-1", name: "Zzz", description: "", picture: ""),
                            Sign(code: "Z-2", name: "ZZZ", description: "", picture: "")])
                     ]

I need to get one random element of any category (not one from each) from this base and print it as sign.code

I prepared the variable to store the value:

var RandomSign: Sign

And tried to do it with for loop:

    func randomSign() {
            for categorie in categories {
                randomSign = categorie.sign.randomElement()

But, in the result, my loop generate me random element from each category, and finally save only random from the last one. I would like print for example "X-2" in my consol as random selected value.

CodePudding user response:

Why not pick a random category and then a random sign from that random category?

func randomSign() {
    randomSign = categories.randomElement()!.sign.randomElement()!
}

This code will crash if any of the arrays are empty. It would be safer if randomSign was optional then you can do:

func randomSign() {
    randomSign = categories.randomElement()?.sign.randomElement()
}

Or you could fallback to a default Sign:

func randomSign() {
    randomSign = categories.randomElement()?.sign.randomElement() ?? Sign(code: "empty", name: "***", description: "", picture: "")
}
  • Related