All you have to do is add characters before the index. The compiler also gives you a hint to add String.CharacterView corresponding to start ##String.CharacterView . The message may be a little fuzzy, but it contains a lot of meaning! Tells you that an array of characters is expected. However, as @vadian suggests, you can even omit characters from the start.
I also wrote a little test 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]
source share