This solution with two integers works, but I'd like to use a range instead:
extension String {
subscript(start: Int, end: Int) -> String? {
return String(self[index(startIndex, offsetBy: start#)...index(startIndex, offsetBy: end)])
}
}
The two following solutions use ranges, but both produce the same error, not in the extension code, but when attempting to use it:
'subscript' is unavailable: cannot subscript String with an integer range.
This is an absurd error that's basically telling me there is no range subscript for String, when in fact I just created it, so it DOES exist.
extension String {
subscript(range: Range<String.IndexDistance>) -> String? {
return String(self[index(startIndex, offsetBy: range.startIndex)...index(startIndex, offsetBy: range.endIndex)])
}
subscript(range: Range<Int>) -> String? {
return String(self[index(startIndex, offsetBy: range.startIndex)...index(startIndex, offsetBy: range.endIndex)])
}
}
let greeting = "Hello, World"
print(greeting[0...4]) // should print "Hello"