ios 替换 Swift 3 中数组的 indexOf(_:) 方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38351213/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Replacement for array's indexOf(_:) method in Swift 3
提问by krlbsk
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 编写)中,我想使用indexOf(_:)
方法(存在于 Swift 2.2 中)从数组中检索元素的索引,但我找不到任何替代方法。
Is there any good replacement for that method in Swift 3 or anything that act similar?
在 Swift 3 或任何类似的方法中有什么好的替代方法吗?
Update
更新
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”时没有任何提示。但是,当我尝试获取诸如Int
代码完成之类的构建类型的索引时,我可以使用index(of:)
方法。
回答by Tim Vermeulen
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:
indexOf(_:)
已更名为index(of:)
对符合类型Equatable
。您可以使任何类型符合Equatable
,这不仅适用于内置类型:
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(_:)
that takes a closure has been renamed to index(where:)
:
indexOf(_:)
需要关闭的已重命名为index(where:)
:
[1, 3, 5, 4, 2].index(where: { class MyClass {
var key: String?
}
extension MyClass: Equatable {
static func == (lhs: MyClass, rhs: MyClass) -> Bool {
return MyClass.key == MyClass.key
}
}
> 3 }) // 2
// or with a training closure:
[1, 3, 5, 4, 2].index { struct MyClass: Equatable {
let title: String
public static func ==(lhs: MyClass, rhs: MyClass) -> Bool {
return lhs.title == rhs.title
}
}
> 3 } // 2
回答by Sean
回答by kans
This worked for me in Swift 3 without an extension:
这在没有扩展的 Swift 3 中对我有用:
##代码##