在 Swift2 中,如何对包含可选值的数组执行 indexOf
操作?以下示例将无法编译:
var strings: [String?] = ["hello", nil, "world"]
let index = strings.indexOf("world")
编译器提示
“无法使用类型为“(String)”的参数列表调用indexOf”
没有 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")
最佳答案
或者更简单:
let strings: [String?] = ["hello", nil, "world"]
strings.indexOf{ $0 == "world" }
这之所以有效,是因为 ==
也为可选值定义了
关于arrays - 如何对带有选项的数组执行indexOf?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32050834/