I know we can use subscript to cut a part of the string in Swift 4, .
let s = "aString"
let subS = s[..<s.endIndex]
But the problem is, how to cut the s
to a subString like aStr
.
I mean, What I want to do is something like s[..<(s.endIndex-3)]
.
But it's not right.
So, how to do it in Swift 4.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With