当 bool 参数设置为时,这意味着什么? 1.0:0.0?
What does it mean when a bool parameter is set to ? 1.0: 0.0?
我正在学习教程,其中一个参数是布尔值:
func fadeImageView(imageView: UIImageView, toImage: UIImage, showEffects:Bool) {
}
但是在函数体中提供的 bool 值是:
self.view.alpha = showEffects ? 1.0: 0.0
我假设 bool 只能有 true 或 false 值。这是什么? 1.0: 0.0 是什么意思?
是 ternary conditional operator。 a ? b : c
returns b
如果 a
计算结果为真,否则 c
。
self.view.alpha
不是布尔值 属性。是CGFloat
.
您还没有将 Bool
分配给 alpha 属性。您示例中的三元运算符表示 "If showEffects
is true
, make the alpha 1.0, otherwise 0.0"
这里有两件事,所以我会一一回答。
view.alpha
不是 Bool
,它是 CGFloat
,有效值介于 1.0
和 0.0
之间。例如,0.5
的 alpha 是 50% 不透明的。
?:
是一个特殊的运算符。与执行 2 个值的运算的 +
或 *
不同,?:
执行 3 个值的运算。这就是它被称为 ternary operator
的原因。第一个值是一个条件,它将被评估为 true
或 false
。第二个值是条件为 true
时的运算结果。第三个值是条件为false
.
时的运算结果
<conditional value> ? <when true value> : <when false value>
等同于:
func ternaryOperation(_ conditionalValue: Bool, _ whenTrueValue: CGFloat, _ whenFalseValue: CGFloat) -> CGFloat {
if (conditionalValue) {
return whenTrueValue
} else {
return whenFalseValue
}
}
…
self.view.alpha = ternaryOperation(showEffects, 1.0, 0.0)
我正在学习教程,其中一个参数是布尔值:
func fadeImageView(imageView: UIImageView, toImage: UIImage, showEffects:Bool) {
}
但是在函数体中提供的 bool 值是:
self.view.alpha = showEffects ? 1.0: 0.0
我假设 bool 只能有 true 或 false 值。这是什么? 1.0: 0.0 是什么意思?
是 ternary conditional operator。 a ? b : c
returns b
如果 a
计算结果为真,否则 c
。
self.view.alpha
不是布尔值 属性。是CGFloat
.
您还没有将 Bool
分配给 alpha 属性。您示例中的三元运算符表示 "If showEffects
is true
, make the alpha 1.0, otherwise 0.0"
这里有两件事,所以我会一一回答。
view.alpha
不是 Bool
,它是 CGFloat
,有效值介于 1.0
和 0.0
之间。例如,0.5
的 alpha 是 50% 不透明的。
?:
是一个特殊的运算符。与执行 2 个值的运算的 +
或 *
不同,?:
执行 3 个值的运算。这就是它被称为 ternary operator
的原因。第一个值是一个条件,它将被评估为 true
或 false
。第二个值是条件为 true
时的运算结果。第三个值是条件为false
.
<conditional value> ? <when true value> : <when false value>
等同于:
func ternaryOperation(_ conditionalValue: Bool, _ whenTrueValue: CGFloat, _ whenFalseValue: CGFloat) -> CGFloat {
if (conditionalValue) {
return whenTrueValue
} else {
return whenFalseValue
}
}
…
self.view.alpha = ternaryOperation(showEffects, 1.0, 0.0)