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

下面是完整的例子:

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

当前回答

斯威夫特4/5

var str = "bla"
str.removeLast() // returns "a"; str is now "bl"

其他回答

全局的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())

这是一个字符串扩展表单:

extension String {

    func removeCharsFromEnd(count_:Int) -> String {
        let stringLength = count(self)

        let substringIndex = (stringLength < count_) ? 0 : stringLength - count_

        return self.substringToIndex(advance(self.startIndex, substringIndex))
    }
}

对于Swift 1.2之前的版本:

...
let stringLength = countElements(self)
...

用法:

var str_1 = "Maxim"
println("output: \(str_1.removeCharsFromEnd(1))") // "Maxi"
println("output: \(str_1.removeCharsFromEnd(3))") // "Ma"
println("output: \(str_1.removeCharsFromEnd(8))") // ""

参考:

扩展向现有的类、结构或枚举类型添加新功能。这包括扩展您无法访问原始源代码的类型的能力(称为回溯建模)。扩展类似于Objective-C中的类别。(与Objective-C类别不同,Swift扩展没有名称。)

看文档

斯威夫特4/5

var str = "bla"
str.removeLast() // returns "a"; str is now "bl"

斯威夫特4

var welcome = "Hello World!"
welcome = String(welcome[..<welcome.index(before:welcome.endIndex)])

or

welcome.remove(at: welcome.index(before: welcome.endIndex))

or

welcome = String(welcome.dropLast())

简单回答(2015-04-16有效):removeAtIndex(mystring . endindex .前任())

例子:

var howToBeHappy = "Practice compassion, attention and gratitude. And smile!!"
howToBeHappy.removeAtIndex(howToBeHappy.endIndex.predecessor())
println(howToBeHappy)
// "Practice compassion, attention and gratitude. And smile!"

元:

语言继续着它的快速进化,使得许多以前很好的sos答案的半衰期变得危险地短暂。学习语言并参考真正的文档总是最好的。