0

Code:

let startIndex = oldString.characters.index(oldString.startIndex, offsetBy: range.location)

let endIndex = String.Characterview corresponding to 'startIndex' .index(startIndex, offsetBy: 5)

Prior to migrating to Swift 3, the above line was:

let endIndex = startIndex.advancedBy(5)

I know the docs say that advancedBy should be converted to:

Collection.index(index, offsetBy: delta)

but when I do the above code I get this error:

Protocol Collection can only be used as a generic constraint because it has Self or associated type requirements

Question:

So what is it that I need to do here? I feel like this is something simple and I'm just barley missing it. I've been all over the docs and the internet.

ChintaN -Maddy- Ramani
  • 5,156
  • 1
  • 27
  • 48
Justin
  • 315
  • 2
  • 4
  • 18
  • 1
    Hi there. There's an extensive discussion of this topic at http://stackoverflow.com/questions/39677330/how-does-substring-work-in-swift-3 which I think will help you out. – Marcus Sep 28 '16 at 05:27

1 Answers1

0

Generally, you could get String.Index by using these method:

  • startIndex
  • endIndex
  • index(before: String.Index)
  • index(after: String.Index)
  • index(i: String.Index, offsetBy: String.IndexDistance)
  • index(i: String.Index, offsetBy: String.IndexDistance, limitedBy: String.Index)

then you can use String.substring as usual.

let testStr = "1234567890abcdefghij"

//string length
let testStrLengh = testStr.characters.count

//get tail 10 characters
let tail1 = testStr[testStr.index(testStr.endIndex, offsetBy: -10)..<testStr.endIndex]
let tail2 = testStr.substring(from: testStr.index(testStr.endIndex, offsetBy: -10))

//get head 10 characters
let head1 = testStr[testStr.startIndex..<testStr.index(testStr.startIndex, offsetBy: 10)]
let head2 = testStr.substring(to: testStr.index(testStr.startIndex, offsetBy: 10))

//get centre 10 characters
let startIndex = testStr.index(testStr.startIndex, offsetBy: 5)
let endIndex = testStr.index(testStr.endIndex, offsetBy: -5)
let centreStr = testStr.substring(with: startIndex..<endIndex)
Chen Wei
  • 521
  • 4
  • 10
  • So I basically did 'oldString.index(startIndex, offsetBy: 5)' I think that's what I wanted? – Justin Sep 28 '16 at 15:49
  • 'oldString.index(startIndex, offsetBy: 5)' gives a five-bits string starts from `startIndex`. If thats what you want, yes it is. – Chen Wei Sep 29 '16 at 01:40