Joe Blow Joe Blow - 2 months ago 33
Swift Question

"Collection corresponding..." error on Swift 3 upgrade

Here's a pre-Xcode-8 Swift call ..

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)
}
}


using the automatic upgrade to Swift3, I got these errors...

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)
}
}


What is the solution in Swift3 ??

Answer

See SE-0065: 'Collections move their indices' – in this case you can just replace the editor placeholders with 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)
    }
}

Although note that String isn't a Collection itself, it just implements some convenience methods for indexing that forward to t.characters, which is a Collection.