简体   繁体   English

在Swift中使用firstIndex(of:Element)

[英]Using firstIndex(of: Element) in Swift

I have the following code in Swift 4, on Xcode 10 我在Xcode 10的Swift 4中有以下代码

        var newCard = deck.randomElement()!

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

I'm trying to take a random element from deck: [SetCard] and place it into dealtCards: [SetCard] 我正在尝试从deck: [SetCard]随机抽取一个元素deck: [SetCard]并将其放入dealtCards: [SetCard]

However, Xcode gives me the following error: 但是,Xcode给我以下错误: Xcode错误

I've been looking through the documentation, but as far as I can tell, func firstIndex(of element: Element) -> Int? 我一直在浏览文档,但据我所知, func firstIndex(of element: Element) -> Int? is a method that exists in Array , so I don't understand why Xcode wants me to change 'of' to 'where', when the function has the exact behaviour I want. Array中存在的一种方法,所以我不明白当函数具有所需的确切行为时,为什么Xcode希望我将“ of”更改为“ where”。

What am I missing here? 我在这里想念什么?

The problem has been already explained in the other answers. 该问题已经在其他答案中得到了解释。 Just for the sake of completeness: If you choose a random index instead of a random element in the array then the problem is avoided and the code simplifies to 仅出于完整性考虑:如果您选择随机索引而不是数组中的随机元素,则可以避免该问题并将代码简化为

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

Your deck array elements should conform to Equatable protocol, 您的deck数组元素应符合Equatable协议,

For example as String conforms to Equatable protocol, the below code snippet works, 例如,由于String符合Equatable协议,因此以下代码段有效,

var arr = ["1", "2", "3"]
let newCard = arr.randomElement()!
arr.remove(at: arr.firstIndex(of: newCard)!)

The problem is that your SetCard type has not been declared Equatable. 问题在于您的SetCard类型尚未声明为Equatable。 Thus there is no way to know if a card is present or what its index is, because the notion of a card that “matches” your newCard is undefined. 因此,没有办法知道卡是否存在或其索引是什么,因为与您的newCard “匹配”的卡的概念是不确定的。

(The compiler error message is not as helpful on this point as it could be. That is a known issue. Bug reports have been filed.) (在这一点上,编译器错误消息可能没有帮助。这是一个已知问题。已提交了错误报告 。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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