尝试分配时出现Swift错误:newString = oldString.removeLast(Int)

时间:2017-11-13 14:54:13

标签: swift string

我没有看到一些非常基本的东西w /分配Swift字符串方法的结果(Swift 4,Xcode 9.1 playground)。 anyString.removeLast(X)可以自行正常工作,最后用x少字符修改anyString,但是如果我尝试将结果赋值给声明的变量,比如:newString = anyString.removeLast(X),我得到一个错误。以下是结果示例或注释失败:

var address = "St. James St."
var searchedFor = "St."
var replaceWith = "Street"
var standardAddress = ""
if address.hasSuffix(searchedFor) {
    address.removeLast(searchedFor.count)
    standardAddress = address + replaceWith
}
print(standardAddress)
// prints: St. James Street

但这失败了:

var address = "St. James St."
var searchedFor = "St."
var replaceWith = "Street"
var standardAddress = ""
if address.hasSuffix(searchedFor) {
    standardAddress = address.removeLast(searchedFor.count) + replaceWith
    // error: type 'inout String' does not conform to protocol 'BidirectionalCollection' standardAddress = address.removeLast(searchedFor.count) + replaceWith
}
print(standardAddress)

这也失败了,不同的Xcode游乐场错误:

var address = "St. James St."
var searchedFor = "St."
var replaceWith = "Street"
var standardAddress = ""
if address.hasSuffix(searchedFor) {
    standardAddress = address.removeLast(searchedFor.count)
    // error: cannot assign value of type '()' to type 'String' standardAddress = address.removeLast(searchedFor.count)
}
print(standardAddress)

感谢您帮助我了解上述差异。

0 个答案:

没有答案