Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/macos/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios Swift:使用索引和元素进行迭代_Ios_Macos_Swift - Fatal编程技术网

Ios Swift:使用索引和元素进行迭代

Ios Swift:使用索引和元素进行迭代,ios,macos,swift,Ios,Macos,Swift,我想在Swift中实现类似于默认查找的功能,但它接受comparator: func find<C : CollectionType>(domain: C, comparator: (C.Generator.Element) -> Bool) -> C.Index? { for (index, element) in enumerate(domain) { if comparator(element) { return in

我想在Swift中实现类似于默认查找的功能,但它接受comparator:

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
}
枚举返回Int类型的元组C.Generator.Element的问题,而我需要C.Index,C.Generator.Element。我搜索了很多,但没有找到如何使用C.Index类型进行迭代

编辑


对不起,是打字错误。我的意思是枚举而不是生成

作为空速注释,我想你的意思是枚举而不是生成。但是,您需要的工具是索引,以获取集合的所有索引:

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
}

最简单的解决方案是使用索引而不是枚举,然后使用下标获取值:

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
}
编辑:正如Rob在下面指出的,根据swift文档,这是保证有效的


然而,这依赖于一些让我有点不安的东西,即假设通过集合的生成器对集合进行迭代可以保证返回值的顺序与它们被索引的顺序相同。对于一个集合来说,不这样做可能会有点令人讨厌,因为大多数集合都使用IndexingGenerator为它们的生成器提供服务,所以很可能是这样。但我不认为这是一种保证,因此可能会被认为是不确定的。

你是说enumerate not generate,对吗?我相信这在CollectionType的定义中得到了充分的证明:元素的序列视图与collection视图相同。换句话说,以下代码将与self{}中的x相同的值序列绑定到x:///对于startIndex中的i..啊哈,你是对的,在这种情况下,我收回了我的不安,并决定我喜欢这个解决方案:很高兴你利用这一刻来教Zip2。如此强大,如此缺乏探索。你知道吗,一天两个Zip2答案
func find<C : CollectionType>(domain: C, comparator: (C.Generator.Element) -> Bool) -> C.Index? {
    for (index, element) in Zip2(indices(domain), domain) {
        if comparator(element) {
            return index
        }
    }

    return nil
}