In Swift 4, I\'m getting this error when I try to take a Substring
of a String
using subscript syntax.
\'subscript\' is unavaila
Based on p-sun's answer
Swift 4
extension StringProtocol {
subscript(bounds: CountableClosedRange<Int>) -> SubSequence {
let start = index(startIndex, offsetBy: bounds.lowerBound)
let end = index(start, offsetBy: bounds.count)
return self[start..<end]
}
subscript(bounds: CountableRange<Int>) -> SubSequence {
let start = index(startIndex, offsetBy: bounds.lowerBound)
let end = index(start, offsetBy: bounds.count)
return self[start..<end]
}
}
Notable changes:
StringProtocol
. This allows adopters such as Substring
to also gain these subscripts.String
twice. The index
method is O(n) where n is the offset from i.Your question (and self-answer) has 2 problems:
Subscripting a string with Int
has never been available in Swift's Standard Library. This code has been invalid for as long as Swift exists:
let mySubstring: Substring = myString[1..<3]
The new String.Index(encodedOffset: )
returns an index in UTF-16 (16-bit) encoding. Swift's string uses Extended Grapheme Cluster, which can take between 8 and 64 bits to store a character. Emojis make for very good demonstration:
let myString = "