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、斯威夫特
基础教程推荐
- 如何将图像从一项活动发送到另一项活动? 2022-01-01
- iOS - UINavigationController 添加多个正确的项目? 2022-01-01
- 为什么姜饼模拟器方向卡在应用程序中? 2022-01-01
- Play 商店的设备兼容性问题 2022-01-01
- Android Volley - 如何动画图像加载? 2022-01-01
- navigationItem.backBarButtonItem 不工作?为什么上一个菜单仍然显示为按钮? 2022-01-01
- Xcode UIView.init(frame:) 只能在主线程中使用 2022-01-01
- SwiftUI-ScrollViewReader的ScrollTo不滚动 2022-01-01
- 如何比较两个 NSDate:哪个是最近的? 2022-01-01
- UIImage 在开始时不适合 UIScrollView 2022-01-01
