Swift 3升级时出现“收集对应...”错误

时间:2016-09-20 06:38:50

标签: swift swift3 xcode8

这是一个Xcode-8之前的Swift调用..

func gappizeAtDoubleNewlines()
    {
    let t = self.text!
    var index = t.startIndex
    var follow = index.advancedBy(1)

    for i in 0 ..< (t.characters.count-4)
        {
        let r = index ... follow
        if ( t.substringWithRange(r) == "\n\n" )
            { alterLineGapHere(i) }

        index = index.advancedBy(1)
        follow = index.advancedBy(1)
        }
    }

使用自动升级到Swift3,我收到了这些错误......

enter image description here

in text,

func gappizeAtDoubleNewlines()
    {
    let t = self.text!
    var index = t.startIndex
    var follow = <#T##Collection corresponding to `index`##Collection#>.index(index, offsetBy: 1)

    for i in 0 ..< (t.characters.count-4)
        {
        let r = index ... follow
        if ( t.substring(with: r) == "\n\n" )
            { alterLineGapHere(i) }

        index = <#T##Collection corresponding to `index`##Collection#>.index(index, offsetBy: 1)
        follow = <#T##Collection corresponding to `index`##Collection#>.index(index, offsetBy: 1)
        }
    }

Swift3中的解决方案是什么?

1 个答案:

答案 0 :(得分:3)

请参阅SE-0065: 'Collections move their indices' - 在这种情况下,您只需将编辑器占位符替换为t

func gappizeAtDoubleNewlines() {

    let t = self.text!
    var index = t.startIndex

    // Note that because substring(by:) takes a Range<String.Index>, rather than
    // a ClosedRange, we have to offset the upper bound by one more.
    var follow = t.index(index, offsetBy: 2)

    for i in 0 ..< (t.characters.count-4) {
        let r = index ..< follow
        if (t.substring(with: r) == "\n\n") {
            alterLineGapHere(i)
        }

        index = t.index(index, offsetBy: 1)
        follow = t.index(follow, offsetBy: 1)
    }
}

虽然请注意String不是Collection本身,但它只是实现了一些方便的方法,用于将转发索引到t.characters,其中 a Collection