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)