我如何从字符串变量使用Swift删除最后一个字符?在文档中找不到。

下面是完整的例子:

var expression = "45+22"
expression = expression.substringToIndex(countElements(expression) - 1)

当前回答

Swift 3:当你想删除尾随字符串:

func replaceSuffix(_ suffix: String, replacement: String) -> String {
    if hasSuffix(suffix) {
        let sufsize = suffix.count < count ? -suffix.count : 0
        let toIndex = index(endIndex, offsetBy: sufsize)
        return substring(to: toIndex) + replacement
    }
    else
    {
        return self
    }
}

其他回答

Swift 3(根据文档)2016年11月20日

let range = expression.index(expression.endIndex, offsetBy: -numberOfCharactersToRemove)..<expression.endIndex
expression.removeSubrange(range)

全局的dropLast()函数作用于序列,因此也作用于字符串:

var expression  = "45+22"
expression = dropLast(expression)  // "45+2"

// in Swift 2.0 (according to cromanelli's comment below)
expression = String(expression.characters.dropLast())

修剪字符串最后一个字符最简单的方法是:

title = title[title.startIndex ..< title.endIndex.advancedBy(-1)]

使用新的Substring类型用法:

斯威夫特4:

var before: String = "Hello world!"
var lastCharIndex: Int = before.endIndex
var after:String = String(before[..<lastCharIndex])
print(after) // Hello world

短:

var before: String = "Hello world!"
after = String(before[..<before.endIndex])
print(after) // Hello world

Swift 3:当你想删除尾随字符串:

func replaceSuffix(_ suffix: String, replacement: String) -> String {
    if hasSuffix(suffix) {
        let sufsize = suffix.count < count ? -suffix.count : 0
        let toIndex = index(endIndex, offsetBy: sufsize)
        return substring(to: toIndex) + replacement
    }
    else
    {
        return self
    }
}