George Asda
George Asda

Reputation: 2129

Boolean with swift

This is really confusing. Does anyone have any ideas?

let viewHasMovedToRight == false //initially I want this to be false

then

func moveViewToRight(sender: UIButton!) {
        if viewHasMovedToRight == false {               
            viewHasMovedToRight == true;

            UIView.animateWithDuration(
                0.75,
                animations: {},
                completion: { (value: Bool) in
                     println(" moved")                     
                }
            )
        }                
        else {                
            viewHasMovedToRight == false;             
            UIView.animateWithDuration(
                0.75,
                animations:{},
                completion:{ (value: Bool) in                     
                    println("not moved")                       
                }
            )
        }

       // println("move view")
    }

Only the first if is called. I cannot re-assign the value back to true...

Something that was so easy on Obj-C now with swift is so frustrating...

Upvotes: 4

Views: 38076

Answers (4)

paulomatsui
paulomatsui

Reputation: 151

Newbie here. I used to do that mistake all the time, using = both for assign and to compare. Use = to assign and == to compare

Upvotes: 0

casillas
casillas

Reputation: 16793

@George, you should use set operator

let viewHasMovedToRight = false

not comparison operator

let viewHasMovedToRight == false

Upvotes: 3

rob mayoff
rob mayoff

Reputation: 385600

You have two problems.

One, you are using == (which tests for equality) where you should be using = (which assigns a value). Two, you are declaring a constant and then trying to assign a new value to it later. You need to declare a variable.

var viewHasMovedToRight = false

...
    viewHasMovedToRight = true

Also, most people would find this if condition more understandable:

if !viewHasMovedToRight {

And it would be even simpler if you were to reverse the order of your if clauses:

if viewHasMovedToRight {
    viewHasMovedToRight = false
    ...
} else {
    viewHasMovedToRight = true
    ...
}

Upvotes: 22

AdamPro13
AdamPro13

Reputation: 7400

let viewHasMovedToRight = false not let viewHasMovedToRight == false

EDIT: It looks like you use == instead of = everywhere you are setting the boolean.

Upvotes: 5

Related Questions