替换Swift 3中数组的indexOf(_ :)方法 [英] Replacement for array's indexOf(_:) method in Swift 3
问题描述
在我的项目中(用Swift 3编写)我想使用 indexOf(_:)
方法(存在于Swift 2.2中)从数组中检索元素的索引,但是我找不到任何替代品。
In my project (written in Swift 3) I want to retrieve index of an element from array using indexOf(_:)
method (existed in Swift 2.2), but I cannot find any replacement for that.
在Swift 3或类似的任何行为中,是否有任何替代方法?
Is there any good replacement for that method in Swift 3 or anything that act similar?
更新
我忘记提及我想在自定义对象中搜索。在代码完成时,我没有在输入'indexof'时得到任何提示。但是,当我尝试获取类似 Int
类型的构建索引时,代码完成工作,我可以使用 index(of :)
方法。
I forget to mention that I want to search in custom object. In code completion I haven't got any hints when typing 'indexof'. But when I try to get index of build in type like Int
code completion works and I could use index(of:)
method.
推荐答案
indexOf(_:)
已重命名为符合 Equatable
的类型的 index(of:)
。您可以将任何类型符合 Equatable
,它不仅适用于内置类型:
indexOf(_:)
has been renamed to index(of:)
for types that conform to Equatable
. You can conform any of your types to Equatable
, it's not just for built-in types:
struct Point: Equatable {
var x, y: Int
}
func == (left: Point, right: Point) -> Bool {
return left.x == right.x && left.y == right.y
}
let points = [Point(x: 3, y: 5), Point(x: 7, y: 2), Point(x: 10, y: -4)]
points.index(of: Point(x: 7, y: 2)) // 1
带有闭包的indexOf(_:)
已重命名为 index(其中:) / code>:
indexOf(_:)
that takes a closure has been renamed to index(where:)
:
[1, 3, 5, 4, 2].index(where: { $0 > 3 }) // 2
// or with a training closure:
[1, 3, 5, 4, 2].index { $0 > 3 } // 2
这篇关于替换Swift 3中数组的indexOf(_ :)方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!