How to find the index of a tuple element from an tuple array? iOS, Swift(如何从元组数组中找到元组元素的索引?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、斯威夫特


基础教程推荐
- iOS4 创建后台定时器 2022-01-01
- AdMob 广告未在模拟器中显示 2022-01-01
- navigator.geolocation.getCurrentPosition 在 Android 浏览器上 2022-01-01
- libGDX 从精灵或纹理中获取像素颜色 2022-01-01
- iPhone - 获取给定地点/时区的当前日期和时间并将其与同一地点的另一个日期/时间进行比较的正确方法 2022-01-01
- Android:getLastKnownLocation(LocationManager.NETWORK_PROVIDER 2022-01-01
- Cocos2d iPhone 非矩形精灵触摸检测 2022-01-01
- NSString intValue 不能用于检索电话号码 2022-01-01
- 如何从 logcat 中删除旧数据? 2022-01-01
- 通过重定向链接在 Google Play 中打开应用 2022-01-01