Lodewijck
Lodewijck

Reputation: 416

Swift: logical not operator not working

this piece of code prints two times 'false':

println(levelController?.died)
println(!levelController?.died)

I don't understand why, the levelController is instantiated and the died attribute is declared in LevelController like this:

var died = false

Can someone tell me what I might be doing wrong?

Upvotes: 0

Views: 2196

Answers (3)

tBug
tBug

Reputation: 827

You can create your own not operator like this:

let not = (!)

And now we can assign a bool to test this:

let dead = false

if not(dead) {
print(dead)
// Code
} else {
// Code
}

Upvotes: 3

gnasher729
gnasher729

Reputation: 52538

This is Swift, not Objective C.

levelController?.died is not a boolean value. It is an optional boolean. It can be true, false, or nil. The first println prints false. The logical not operator, applied to an optional, returns false if the optional is not nil, and true if the optional is nil. Just as it does in C when applied to a pointer.

Upvotes: 1

ColinE
ColinE

Reputation: 70122

As a complete example, your code:

class Controller {
  var died: Bool = false
}

var levelController: Controller? = Controller()

println(levelController?.died)
println(!levelController?.died)

Outputs the following:

Optional(false)
false

The first version of your code levelController?.died makes use of option chaining, unwrapping the levelController and accessing the died property. This explains why the output is Optional(false). You would typically use it as follows:

if let died = levelController?.died {
  if (died) {
    println("I died")
  }
}

The if-let statements unwraps this optional value.

The second version of your code !levelController?.died tests whether the given optional value is nil or not. You will notice that changing died to true of false makes no difference.

However, changing the instantiation as follows:

var levelController: Controller? = nil

Results in !levelController?.died becoming true. This isn't really a terribly practical piece of code!

Upvotes: 0

Related Questions