update: Xcode 9 ? Swift 4 or later
String now conforms to RangeReplaceableCollection so you can use collection method dropLast straight in the String and therefore an extension it is not necessary anymore. The only difference is that it returns a Substring. If you need a String you need to initialize a new one from it:
let string = "0123456789"
let substring1 = string.dropLast(2) // "01234567"
let substring2 = substring1.dropLast() // "0123456"
let result = String(substring2.dropLast()) // "012345"
We can also extend LosslessStringConvertible
to add trailing syntax which I think improves readability:
extension LosslessStringConvertible {
var string: String { .init(self) }
}
Usage:
let result = substring.dropLast().string
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…