gpt4 book ai didi

ios - 使用 firstIndex(: Element) in Swift

转载 作者:行者123 更新时间:2023-11-28 09:48:42 26 4
gpt4 key购买 nike

我在 Xcode 10 上的 Swift 4 中有以下代码

        var newCard = deck.randomElement()!

deck.remove(at: deck.firstIndex(of: newCard)!)
dealtCards.append(newCard)

我正在尝试从 deck: [SetCard] 中取出一个随机元素并将其放入 dealtCards: [SetCard]

但是,Xcode 给我以下错误: Xcode error

我一直在查看文档,但据我所知,func firstIndex(of element: Element) -> Int?Array< 中存在的方法,所以我不明白为什么 Xcode 要我在函数具有我想要的确切行为时将“of”更改为“where”。

我在这里错过了什么?

最佳答案

这个问题已经在其他答案中解释过了。只是为了完整起见:如果您选择随机索引而不是数组中的随机元素,那么问题就可以避免,代码会简化为

if let randomIndex = deck.indices.randomElement() {
let newCard = deck.remove(at: randomIndex)
dealtCards.append(newCard)
} else {
// Deck is empty.
}

关于ios - 使用 firstIndex(: Element) in Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53980082/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com