简体   繁体   中英

Get array element and remove

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)

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM