Chapter 12 page 338

Hi everyone, I am doing the tile map tutorial

can anyone explain me this function in deeper details please (the function is to have special animation depending on which direction my character is moving)

func animationDirection(for directionVector: CGVector)-> Direction {

  let direction: Direction
  //moving forward, backward, left, right
  if abs(directionVector.dy) > abs(directionVector.dx) {
    direction = directionVector.dy < 0 ? .forward : .backward
  } else {
    direction = directionVector.dx < 0 ? .left : .right
  return direction


I specially don’t understand why that question mark is here.

thanks for reading and thanks in advance for your help


Hi @nehemie -

This is a “ternary operator” which is a conditional.

direction = directionVector.dy < 0  ? .forward : .backward

is the same as saying:

if directionVector.dy < 0 {
   direction = .forward
} else {
  direction = .backward

The bit before the ? is the conditional, the bit on the left of the : is the true part and the bit on the right of the : is the false part.

As you can see the ternary operator is more concise, but we only use it for simple assignments such as this one.

it makes more sense to me know , thanks Caroline