-7

I can't quite comprehend this syntax in the return statement. I'm not sure if it is new in Swift 2.0, but what does the ? and the : mean? Is this question mark an optional, even though spaced? Im quite confused, coming from an Objective-C background.

private func doContainsUser(user: User) -> Bool {
    let isInverted = setOfDiff.contains(user)
    let wasInitiallyAdded = setOfCircleUsers.contains(user)

    //What does the ? and the : mean?
    return isInverted ? !wasInitiallyAdded : wasInitiallyAdded
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
Josh O'Connor
  • 4,694
  • 7
  • 54
  • 98
  • 2
    Ternary operator (see also conditional operator, inline if (iif), or ternary if.). More info there: https://en.wikipedia.org/wiki/%3F: In other words: if (isInverted){return !!wasInitiallyAdded}else{ return wasInitiallyAdded} Swift Doc (that explain it also): https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/BasicOperators.html#//apple_ref/doc/uid/TP40014097-CH6-ID71 – Larme Jun 09 '16 at 15:51
  • 4
    Really? It is _exactly_ the same in Objective-C! https://en.wikipedia.org/wiki/%3F: – matt Jun 09 '16 at 15:51
  • Why would you not just `return wasInitiallyAdded ^ isInverted` – Alexander Jun 09 '16 at 16:06
  • @Larme To be clear, this is not *the* ternary operator. This is the *conditional operator*, which is *a* ternary operator. But it also happens to be the only ternary operator at the moment. – Alexander Jun 09 '16 at 16:17

1 Answers1

5

This is a short hand if else statement.

if isInverted {
   return !wasInitiallyAdded
}
else {
   return wasInitiallyAdded
}
egfconnor
  • 2,637
  • 1
  • 26
  • 44