ConteOlaf
ConteOlaf

Reputation: 75

Compare element in Dictionary, Swift

During the generation of my elements I also generate a Dictionary with [key,value]

key is an Int

Value is a string.

I gave an example: [1 : A, 2 : B, 3 : A, 4 : B]

So now I know that first and third elements are a pairs!

I also have a function that rotates my element when tapped. When I tap a card I have access to his ID.

What I need is to compare if the tapped card has the same dictionary value of the second tapped card (and if yes don't rotate anymore this card) else rotate down both card.

This is the function I am talking about:

    @IBAction func actionPerformed(_ sender: UITapGestureRecognizer) {
        if element.transform.rotation.angle == .pi {
            self.firstRotation(element: element)

                } else {
                    self.secondRotation(element: element)

                }

}

So lets wrap up, I already have a dictionary with solutions, what I need is to check if the first tapped card is equal to the second, if yes do something, else do other thing.

Upvotes: 0

Views: 147

Answers (1)

atarasenko
atarasenko

Reputation: 1808

A possible solution is to save the ID of the card to a variable (firstId). If this variable is nil, it means that this is the first tapped card, else it is the second one.

var firstId: Int?

@IBAction func onTap(_ sender: UITapGestureRecognizer) {
    let tapLocation = sender.location(in: arView)
    if let card = arView.entity(at: tapLocation) {
        if let firstId = firstId {
            // second card tapped
            if self.cardEntityCorrelation[firstId] == self.cardEntityCorrelation[card.id] {
                // cards form a pair; no rotation is needed
                // reset firstId to allow selecting the next pair
                self.firstId = nil
            } else {
                // cards do not form a pair
                // rotate second card
                rotate(card: card)
            }
        } else {
            // first card tapped; save id
            firstId = card.id
            // rotate first card
            rotate(card: card)
        }
    }
}

//ROTATE UP OR DOWN
private func rotate(card: Entity) {
    if card.transform.rotation.angle == .pi {
        firstRotation(card: card)
    } else {
        secondRotation(card: card)
    }
}

//ROTATE UP
private func firstRotation(card: Entity) {
    var flipDownTransform = card.transform
    flipDownTransform.rotation = simd_quatf(angle: 0, axis: [1,0,0])
    card.move(to: flipDownTransform, relativeTo: card.parent, duration: 0.25, timingFunction: .easeInOut)
}

//ROTATE DOWN
private func secondRotation(card: Entity) {
    var flipUpTransform = card.transform
    flipUpTransform.rotation = simd_quatf(angle: .pi, axis: [1,0,0])
    card.move(to: flipUpTransform, relativeTo: card.parent, duration: 0.25, timingFunction: .easeInOut)
}

Upvotes: 1

Related Questions