我如何为带有可选值的数组做 indexOf?

How do I do indexOf for arrays with optionals?

在 Swift2 中,如何对包含可选值的数组执行 indexOf?以下示例无法编译:

var strings: [String?] = ["hello", nil, "world"]
let index = strings.indexOf("world")

编译器抱怨

"Cannot invoke indexOf with an argument list of type '(String)'"

没有 indexOf 的天真方法是:

let index: Int = {
    for var i = 0; i < strings.count; i++ {
        let s: String? = strings[i]
        if s == "world" {
            return i
        }
    }
    return -1
}()

没有办法使用内置的indexOf功能吗?

但同样的例子适用于非可选数组:

var strings: [String] = ["hello", "world"]
let index = str.indexOf("world")

您可以使用 "trailing closure" 中的表达式来表示 indexOf:

var arr: [String?] = ["hello", nil, "world"]
let i = arr.indexOf() { [=10=] != nil && [=10=] == "world" }

或者更简单:

let strings: [String?] = ["hello", nil, "world"]
strings.indexOf{ [=10=] == "world" }

之所以有效,是因为 == 也为可选值定义了