Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/18.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
了解Swift指数、范围、距离_Swift_Generics_Collections_Range_Swift Extensions - Fatal编程技术网

了解Swift指数、范围、距离

了解Swift指数、范围、距离,swift,generics,collections,range,swift-extensions,Swift,Generics,Collections,Range,Swift Extensions,我正在实现对Swift的CollectionType的扩展,该扩展提供了在集合中查找子序列以及查找该子序列范围的能力。我在操场上的代码是: extension CollectionType where Generator.Element:Equatable, Index:ForwardIndexType, SubSequence.Generator.Element == Generator.Element { func search<S: CollectionType where

我正在实现对Swift的CollectionType的扩展,该扩展提供了在集合中查找子序列以及查找该子序列范围的能力。我在操场上的代码是:

extension CollectionType where Generator.Element:Equatable, Index:ForwardIndexType, SubSequence.Generator.Element == Generator.Element {
    func search<S: CollectionType where S.Generator.Element == Generator.Element, S.Index:ForwardIndexType>(pattern: S) -> Self.Index? {
        return self.lazy.indices.indexOf{
            self[$0..<self.endIndex].startsWith(pattern)
        }
    }

    func rangeOf<S: CollectionType where S.Generator.Element == Generator.Element, S.Index:ForwardIndexType, Index:ForwardIndexType>(pattern: S) -> Range<Index>? {
        if let start = self.search(pattern) {
            var end = start
            for _ in pattern.startIndex..<pattern.endIndex {
                end = end.advancedBy(1)
            }
            return start..<end
        } else {
            return nil
        }
    }
}
或许

           end = start.advancedBy(pattern.endIndex - pattern.startIndex, limit: self.endIndex)
(我确实认识到limit参数是多余的;省略它在以下方面没有什么区别。)最后两个编译都不能使用类型为“(S.Index.Distance,limit:Self.Index)”的参数列表调用“advancedBy”(错误
)。我的问题是,为什么这两种形式都不能接受?(关于我是否正确地为扩展和函数的类型设置了约束,我想还有其他一些有效的问题,但是由于一个版本可以工作,我现在忽略了这一点。)

未编译,因为集合
self
pattern
需要 没有相同的
索引
类型


如果在
rangeOf()
方法中添加约束,它就会编译。

解决了这个问题后,我发现我可以删除许多其他约束。美好的
            for _ in pattern.startIndex..<pattern.endIndex {
                end = end.advancedBy(1)
            }
            end = start.advancedBy(pattern.count, limit: self.endIndex)
           end = start.advancedBy(pattern.endIndex - pattern.startIndex, limit: self.endIndex)
 end = start.advancedBy(pattern.count, limit: self.endIndex)