In Swift2, how can you do indexOf
on arrays that contain optionals? The following example won't compile:
在Swift2中,如何在包含选项的数组上执行indexOf ?下面的示例无法编译:
var strings: [String?] = ["hello", nil, "world"]
let index = strings.indexOf("world")
with the compiler complaining
与编译器抱怨
"Cannot invoke indexOf with an argument list of type '(String)'"
"不能使用'(String)' '类型的参数列表调用indexOf "
A naive approach without indexOf
would be:
没有索引的幼稚方法是:
let index: Int = {
for var i = 0; i < strings.count; i++ {
let s: String? = strings[i]
if s == "world" {
return i
}
}
return -1
}()
Isn't there any way to use the built-in indexOf
function?
难道没有办法使用内置的indexOf函数吗?
The same example however works for arrays with non-optionals:
同样的例子也适用于非选项数组:
var strings: [String] = ["hello", "world"]
let index = str.indexOf("world")
2 个解决方案
#1
4
Or even simpler:
或者更简单:
let strings: [String?] = ["hello", nil, "world"]
strings.indexOf{ $0 == "world" }
This works because ==
is defined for optionals as well
这是有效的,因为=也是为选项定义的
#2
1
You can use an expression in "trailing closure" for indexOf
:
你可以在indexOf中使用“尾闭包”中的表达式:
var arr: [String?] = ["hello", nil, "world"]
let i = arr.indexOf() { $0 != nil && $0 == "world" }
#1
4
Or even simpler:
或者更简单:
let strings: [String?] = ["hello", nil, "world"]
strings.indexOf{ $0 == "world" }
This works because ==
is defined for optionals as well
这是有效的,因为=也是为选项定义的
#2
1
You can use an expression in "trailing closure" for indexOf
:
你可以在indexOf中使用“尾闭包”中的表达式:
var arr: [String?] = ["hello", nil, "world"]
let i = arr.indexOf() { $0 != nil && $0 == "world" }