如何从元组数组中找到元组元素的索引?iOS、斯威夫特

How to find the index of a tuple element from an tuple array? iOS, Swift(如何从元组数组中找到元组元素的索引?iOS、斯威夫特)

本文介绍了如何从元组数组中找到元组元素的索引?iOS、斯威夫特的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是在tableview cellforrowatindexpath里面

This is inside tableview cellforrowatindexpath

    var valueArray:[(String,String)] = []
    if !contains(valueArray, v: (title,status)) {
                let v = (title,status)
                valueArray.append(v)
            }

这是在 didselectrowatIndexPath 里面

This is inside didselectrowatIndexPath

    let cell = self.tableView.cellForRowAtIndexPath(selectedRow!)
    var newTuple = (cell!.textLabel!.text!, cell!.detailTextLabel!.text!)
    let index = valueArray.indexOf(newTuple)

但我没有得到索引.它抛出一个错误,无法将类型(String,String)"的值转换为预期的参数类型@noescape((String,String)) throws -> Bool".我在这里做错了什么?

But i am not getting the index. It is throwing an error cannot convert value of type '(String,String)' to expected argument type '@noescape ((String,String)) throws -> Bool'. What i am doing wrong here?

推荐答案

可以比较元组是否相等(从 Swift 2.2/Xcode 7.3.1 开始),但是它们不符合 Equatable 协议.因此你有使用 indexOf 的基于谓词的变体来定位元组在一个数组中.示例:

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)
}

Swift 4 中,该方法已重命名为 firstIndex(where:):

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

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

这篇关于如何从元组数组中找到元组元素的索引?iOS、斯威夫特的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何从元组数组中找到元组元素的索引?iOS、斯威夫特

基础教程推荐