[英]Swift: return number < 10
That's the code:那是代码:
import Foundation
func hasAnyMatches(list: [Int], condition: Int -> Bool) -> Bool {
for item in list {
if condition(item) {
return true
}
}
return false
}
func lessThanTen(number: Int) -> Bool {
return number < 10
}
var numbers = [20, 19, 7, 12]
hasAnyMatches(numbers, condition: lessThanTen)
There is a return true
within the if condition and a return false
at the end of func hasAnyMatches()
.有一种
return true
的,如果条件之内,并且return false
在年底func hasAnyMatches()
Why is the return false
needed?为什么需要
return false
?
Without explicitly "telling it" to return something, no function returns false
"automatically".如果没有明确“告诉它”返回某些东西,则没有函数“自动”返回
false
。 I am not writing in swift but I am sure if you take away the return false
it'll throw a warning.我没有快速写作,但我相信如果你取消
return false
它会发出警告。
The lessThanTen
simply returns a bool if the number is smaller than 10.如果数字小于 10,
lessThanTen
只会返回一个布尔值。
number < 10
is a statement checking if something is true
or false
. number < 10
是检查某事是true
还是false
的语句。 Hence the return type bool
of lessThanTen
因此
lessThanTen
的返回类型bool
You can do like, for such condition.对于这种情况,您可以这样做。
let LESS_THAN_TEN = 1
let LESS_THAN_HUNDRED = 2
func hasAnyMatch (list: [Int], condition: Int)-> Bool{
var x = false;
switch condition {
case LESS_THAN_TEN :
for a in list {
if a < 10 {
x = true
break
}
}
break
case LESS_THAN_HUNDRED :
for a in list {
if a < 100 {
x = true
break
}
}
break
default:
x = false
}
return x
}
var isLessThanTen = hasAnyMatch([14, 45, 12, 65], condition: LESS_THAN_TEN)
print(isLessThanTen)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.