在Swift 3中替换array' s indexOf(_ :)方法 [英] Replacement for array's indexOf(_:) method in Swift 3

查看:324
本文介绍了在Swift 3中替换array' s indexOf(_ :)方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的项目(用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(_:)已被重命名为index(of:),用于符合Equatable的类型.您可以使任何类型都符合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(where:):

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中替换array' s indexOf(_ :)方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆