Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a substring in swift 4?

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.

like image 319
JsW Avatar asked Nov 30 '22 08:11

JsW


1 Answers

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"
like image 134
Martin R Avatar answered Dec 15 '22 09:12

Martin R