【发布时间】:2018-04-29 05:46:32
【问题描述】:
如何在 Swift 4 中删除字符串的最后一个字符?我曾经在早期版本的 Swift 中使用 substring,但不推荐使用 substring 方法。
这是我的代码。
temp = temp.substring(to: temp.index(before: temp.endIndex))
【问题讨论】:
标签: swift string substring swift4
如何在 Swift 4 中删除字符串的最后一个字符?我曾经在早期版本的 Swift 中使用 substring,但不推荐使用 substring 方法。
这是我的代码。
temp = temp.substring(to: temp.index(before: temp.endIndex))
【问题讨论】:
标签: swift string substring swift4
dropLast() is your safest bet,因为它处理 nil 和空字符串而不会崩溃 (answer by OverD),但是如果你想返回你删除的字符,请使用 removeLast():
var str = "String"
let removedCharacter = str.removeLast() //str becomes "Strin"
//and removedCharacter will be "g"
一个不同的函数,removeLast(_:)改变了应该删除的字符数:
var str = "String"
str.removeLast(3) //Str
两者的区别在于removeLast()返回被移除的字符,而removeLast(_:)没有返回值:
var str = "String"
print(str.removeLast()) //prints out "g"
【讨论】:
removeLast() 移除并返回集合的最后一个元素。检查:developer.apple.com/documentation/swift/string/…
dropLast,它在应用于空String时返回一个空Substring,而不是崩溃。
你可以使用dropLast()
您可以在Apple documentation找到更多信息
【讨论】:
nil、empty 和 "" 运行良好。
代码的文字 Swift 4 转换是
temp = String(temp[..<temp.index(before: temp.endIndex)])
foo.substring(from: index) 变为 foo[index...]
foo.substring(to: index) 变为 foo[..<index]
在特定情况下,必须从Substring 结果创建一个新的String。
但是the4kmen's answer中的解决方案要好得多。
【讨论】: