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

标签 ios macos swift

我想在 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/

相关文章:

macos - 在 OS X 上安装 readline 6.0

ios - +[UIView onBackgroundRequest :]: unrecognized selector sent to class

ios - 核心数据对象不附加到数组

ios - 同一 App ID 下的 iPhone 和 iPad 版本

ios - CBCentralManager iOS10 和 iOS9

iphone - 如何在 ios 项目中显示 GADInterstitial?

objective-c - NSOutlineView 仅显示 NSTreeController 层次结构的前 2 层

objective-c - 安装后应用程序无法正常运行

ios - 文本文件到字符串数组代码可以在 Playground 中运行,但不能在 Xcode 项目中运行

ios - 如何在 UIWebview 中使用 SDWebImage