How to find the index of a tuple element from an tuple array? iOS, Swift

回眸只為那壹抹淺笑 提交于 2019-12-01 10:26:29

Tuples can be compared for equality (as of Swift 2.2/Xcode 7.3.1), but they do not conform to the Equatable protocol. Therefore you have to use the predicate-based variant of indexOf to locate a tuple in an array. Example:

let valueArray = [("a", "b"), ("c", "d")]
let tuple = ("c", "d")
if let index = valueArray.indexOf({ $0 == tuple }) {
    print("found at index", index)
}

In Swift 4 the method has been renamed to firstIndex(where:):

if let index = valueArray.firstIndex(where: { $0 == tuple }) {
    print("found at index", index)
}

Here is my option to find index of tuples

var tuple: [(key: String, value: AnyObject)] = [("isSwap", true as AnyObject), ("price", 120 as AnyObject)]
if let index = tuple.index(where: {($0.key == "price")}) {
    print(index)
}
//prints 1
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!