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
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 to
start##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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With