0

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 error

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?

2

3 Answers 3

3

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.
}
Sign up to request clarification or add additional context in comments.

1 Comment

Good to know - I suppose it also has better efficiency as well since I don't have to search through the array again to find the index of element.
2

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)!)

Comments

1

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

3 Comments

That seems to have been the issue. Thanks :)
bugs.swift.org/browse/SR-8934 — I’m surprised this isn’t fixed, since the bug is marked resolved.
Seems to be fixed for Swift 5. With a current snapshot the error message is "Argument type '...' does not conform to expected type 'Equatable'”

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.