5
    subscript (r: Range<Int>) -> String {
        let start = startIndex.advancedBy(r.startIndex)
        let end = start.advancedBy(r.endIndex - r.startIndex)
        return self[Range(start: start, end: end)]
    }

Struggling to convert the above subscript in my String extension to swift 3. Below is what happened after I pressed the convert button on Xcode.

        subscript (r: Range<Int>) -> String {
            let start = characters.index(startIndex, offsetBy: r.lowerBound)
            let end = <#T##String.CharacterView corresponding to `start`##String.CharacterView#>.index(start, offsetBy: r.upperBound - r.lowerBound)
            return self[(start ..< end)]
        }

Screenshot of error

  • http://stackoverflow.com/questions/24092884/get-nth-character-of-a-string-in-swift-programming-language has string subscripting methods for Swift 1, 2, 3. – Martin R Dec 25 '16 at 12:34

1 Answers1

4

All you need to do is to add characters in front of index. The complier also gives you a hint to add a String.CharacterView corresponding tostart##String.CharacterView. The message is maybe a bit fuzzy, but it contains great value! Tells you, that is expecting an array of characters. However, as @vadian suggests, you can even omit the characters from the beginning.

I have written a little test as well, just to make sure.

import Foundation

extension String {
    subscript (r: Range<Int>) -> String {
        let start = index(startIndex, offsetBy: r.lowerBound)
        let end = index(start, offsetBy: r.upperBound - r.lowerBound)
        return self[start..<end]
    }
}

let string = "Hello world"
let range = Range(uncheckedBounds: (lower: 0, upper: 2))
let s = string[range] // prints "He"
dirtydanee
  • 6,081
  • 2
  • 27
  • 43