I am getting a compile error saying
我收到编译错误说
Bound value in a conditional binding must be an Optional type
Below is a screenshot of the code
下面是代码的屏幕截图
4 个解决方案
#1
1
You can convert the value of array[index] to an Optional doing something like this:
您可以将array [index]的值转换为Optional,执行以下操作:
if let value = Int?(array[index]){
result += value
}
That's if your array contains Ints. You could also use AnyObject?, but you'll get a warning from xcode.
如果你的数组包含Ints那就是。你也可以使用AnyObject ?,但是你会收到来自xcode的警告。
#2
1
The array
should be declared as Optional type
, take Int?[]
as an example,
该数组应声明为Optional类型,以Int?[]为例,
let array:Int?[] = [nil, 2, 3]
let index = 0
let count = array.count
for index in 0..count {
if let value = array[index] {
println(value)
} else {
println("no value")
}
}
#3
0
if the type of the value of array[index] is of optional, you could simple do like this:
如果array [index]的值的类型是可选的,你可以这么简单:
if let value = array[index]{
result += value
}
#4
0
In this case the compiler is complaining because array isn't a collection of Optional (nil-able) types. If it truly doesn't need to be, you don't actually need that if
, since everything inside the array is guaranteed to be the same type, and that if
statement won't protect you from a out-of-bounds error anyway. So just go with:
在这种情况下,编译器抱怨,因为array不是Optional(nil-able)类型的集合。如果确实不需要,那么实际上并不需要,因为,因为数组中的所有内容都保证是相同的类型,并且if语句无法保护您免受越界错误的影响。所以请继续:
while ++index < length {
result += array[index]
}
or perhaps better:
或者更好:
for value in array {
result += value
}
or even better:
甚至更好:
result = array.reduce(0) { $0 + $1 }
#1
1
You can convert the value of array[index] to an Optional doing something like this:
您可以将array [index]的值转换为Optional,执行以下操作:
if let value = Int?(array[index]){
result += value
}
That's if your array contains Ints. You could also use AnyObject?, but you'll get a warning from xcode.
如果你的数组包含Ints那就是。你也可以使用AnyObject ?,但是你会收到来自xcode的警告。
#2
1
The array
should be declared as Optional type
, take Int?[]
as an example,
该数组应声明为Optional类型,以Int?[]为例,
let array:Int?[] = [nil, 2, 3]
let index = 0
let count = array.count
for index in 0..count {
if let value = array[index] {
println(value)
} else {
println("no value")
}
}
#3
0
if the type of the value of array[index] is of optional, you could simple do like this:
如果array [index]的值的类型是可选的,你可以这么简单:
if let value = array[index]{
result += value
}
#4
0
In this case the compiler is complaining because array isn't a collection of Optional (nil-able) types. If it truly doesn't need to be, you don't actually need that if
, since everything inside the array is guaranteed to be the same type, and that if
statement won't protect you from a out-of-bounds error anyway. So just go with:
在这种情况下,编译器抱怨,因为array不是Optional(nil-able)类型的集合。如果确实不需要,那么实际上并不需要,因为,因为数组中的所有内容都保证是相同的类型,并且if语句无法保护您免受越界错误的影响。所以请继续:
while ++index < length {
result += array[index]
}
or perhaps better:
或者更好:
for value in array {
result += value
}
or even better:
甚至更好:
result = array.reduce(0) { $0 + $1 }