String.Index
is not an integer, and you cannot simply subtract
s.endIndex - 3
, as "Collections move their index", see
A New Model for Collections and Indices on Swift evolution.
Care must be taken not to move the index not beyond the valid bounds.
Example:
let s = "aString"
if let upperBound = s.index(s.endIndex, offsetBy: -3, limitedBy: s.startIndex) {
let subS = String(s[..<upperBound])
} else {
print("too short")
}
Alternatively,
let upperBound = s.index(s.endIndex, offsetBy: -3, limitedBy: s.startIndex) ?? s.startIndex
let subS = String(s[..<upperBound])
which would print an empty string if s
has less then 3 characters.
If you want the initial portion of a string then you can simply do
let subS = String(s.dropLast(3))
or as a mutating method:
var s = "aString"
s.removeLast(min(s.count, 3))
print(s) // "aStr"