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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Why local notification is not firing for UNCalendarNotificationTrigger(为什么没有为UNCalendarNotificationTrigger触发本地通知)
iOS VoiceOver functionality changes with Bundle Identifier(IOS画外音功能随捆绑包标识符而变化)
tabbar middle tab out of tabbar corner(选项卡栏中间的选项卡角外)
Pushing UIViewController above UITabBar(将UIView控制器推送到UITabBar上方)
Dropbox Files.download does not start when number of files in folder is gt; 1000(当文件夹中的文件数为1000时,Dropbox Files.Download不会启动)
How can I sync two flatList scroll position in react native(如何在本机Reaction中同步两个平面列表滚动位置)