Home > Mobile >  Get array element and remove
Get array element and remove

Time:10-24

I've array with several elements, I want to generate a random element from that array and after generating I want to remove that element. I tried remove method but it returns an error Cannot find 'randSachmeli' in scope randSachmeli is a random generated array

struct SachmelebiData {
    let name:String
    let link:String
}

var mainMenu:[SachmelebiData] = [
    SachmelebiData(name: "ხინკალი", link: ""),
    SachmelebiData(name: "მწვადი", link: ""),
    SachmelebiData(name: "yleyveri", link: "")
]
let yvelaSachmeli:[SachmelebiData] = mainMenu

        var randSachemli = yvelaSachmeli.randomElement()
        yvelaSachmeli.remove(randSachmeli)

CodePudding user response:

Get random elements from the index by getting random index from array indices. And then delete the element by index.

var yvelaSachmeli:[SachmelebiData] = mainMenu

// Get the random element from the array
guard let randomIndexFromArray = yvelaSachmeli.indices.randomElement() else {
    return
}
// Get the element from the index
var randSachemli = yvelaSachmeli[randomIndexFromArray]

// Remove the element by index
yvelaSachmeli.remove(at: randomIndexFromArray)
  • Related