ios 布尔与 swift
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26514204/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Boolean with swift
提问by George Asda
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...
只有第一个if
被调用。我无法将值重新分配回 true...
Something that was so easy on Obj-C now with swift is so frustrating...
现在使用 swift 在 Obj-C 上如此简单的事情是如此令人沮丧......
回答by rob mayoff
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
情况更容易理解:
if !viewHasMovedToRight {
And it would be even simpler if you were to reverse the order of your if
clauses:
如果您要颠倒if
子句的顺序,那就更简单了:
if viewHasMovedToRight {
viewHasMovedToRight = false
...
} else {
viewHasMovedToRight = true
...
}
回答by AdamPro13
let viewHasMovedToRight = false
not let viewHasMovedToRight == false
let viewHasMovedToRight = false
不是 let viewHasMovedToRight == false
EDIT: It looks like you use ==
instead of =
everywhere you are setting the boolean.
编辑:看起来您使用==
而不是=
在您设置布尔值的任何地方。
回答by casillas
@George, you should use set operator
@George,您应该使用 set 运算符
let viewHasMovedToRight = false
not comparison operator
不是比较运算符
let viewHasMovedToRight == false
回答by paulomatsui
Newbie here. I used to do that mistake all the time, using = both for assign and to compare. Use = to assign and == to compare
新手来了 我曾经经常犯这个错误,使用 = 赋值和比较。使用 = 分配,使用 == 进行比较