我想在 Swift 中实现类似于默认 find
的函数,但它接受比较器:
func find<C : CollectionType>(domain: C, comparator: (C.Generator.Element) -> Bool) -> C.Index? {
for (index, element) in enumerate(domain) {
if comparator(element) {
return index
}
}
return nil
}
enumerate
返回 (Int, C.Generator.Element)
类型元组的问题,而我需要 (C.Index, C.Generator.元素)
。我搜索了很多,但没有找到如何使用 C.Index
类型进行迭代。
编辑。
抱歉,这是一个错字。我的意思是枚举
而不是生成
最佳答案
正如 Airspeed Velocity 所指出的,我假设您在这里指的是枚举
,而不是生成
。但是,您需要的工具是 indices
来获取集合的所有索引:
func find<C : CollectionType>(domain: C, comparator: (C.Generator.Element) -> Bool) -> C.Index? {
for index in indices(domain) {
if comparator(domain[index]) {
return index
}
}
return nil
}
关于ios - Swift:使用索引和元素进行迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27695280/