In Swift 4, I'm getting this error when I try to take a Substring
of a String
using subscript syntax.
'subscript' is unavailable: cannot subscript String with a CountableClosedRange, see the documentation comment for discussion
For example:
let myString: String = "foobar"
let mySubstring: Substring = myString[1..<3]
Two questions:
"palindrome"[1..<3]
and "palindrome"[1...3]
, use these extensions.Swift 4
extension String {
subscript (bounds: CountableClosedRange<Int>) -> String {
let start = index(startIndex, offsetBy: bounds.lowerBound)
let end = index(startIndex, offsetBy: bounds.upperBound)
return String(self[start...end])
}
subscript (bounds: CountableRange<Int>) -> String {
let start = index(startIndex, offsetBy: bounds.lowerBound)
let end = index(startIndex, offsetBy: bounds.upperBound)
return String(self[start..<end])
}
}
Swift 3
For Swift 3 replace with return self[start...end]
and return self[start..<end]
.
String.Index
.This is the documentation that Xcode error refers to.