分配数组中项的值会使条件绑定中的Bound值必须为Optional类型

时间:2014-06-04 01:55:42

标签: swift

我收到编译错误

Bound value in a conditional binding must be an Optional type

以下是代码

的屏幕截图

enter image description here

4 个答案:

答案 0 :(得分:1)

您可以将array [index]的值转换为Optional,执行以下操作:

if let value = Int?(array[index]){
    result += value
}

如果你的数组包含Ints那就是。你也可以使用AnyObject ?,但是你会收到来自xcode的警告。

答案 1 :(得分:1)

array应声明为Optional type,以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")
    }
}

答案 2 :(得分:0)

如果array [index]的值的类型是可选的,你可以这么简单地做:

if let value = array[index]{
 result += value
}

答案 3 :(得分:0)

在这种情况下,编译器抱怨,因为数组不是一组Optional(nil-able)类型。如果它真的不需要,那么你实际上并不需要那个if,因为数组中的所有内容都保证是相同的类型,并且if语句赢了&# 39;无论如何都要保护你免受越界错误的影响。所以请继续:

while ++index < length {
    result += array[index]
}

或者更好:

for value in array {
    result += value
}

甚至更好:

result = array.reduce(0) { $0 + $1 }