简体   繁体   中英

Using firstIndex(of: Element) in Swift

I have the following code in Swift 4, on Xcode 10

        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]

However, Xcode gives me the following error: Xcode错误

I've been looking through the documentation, but as far as I can tell, 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.

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,

For example as String conforms to Equatable protocol, the below code snippet works,

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. 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.

(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.)

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