removeSubrange生成'()',而不是预期的上下文结果类型' String'

时间:2017-08-25 17:00:09

标签: swift

static func trimBefore(string: inout String, char: Character) -> String {

    var newString = ""

    if let charRange = string.range(of: String(char)) {
        newString = string.removeSubrange(string.startIndex..<charRange.upperBound)
    }
    return newString
}

static func trimAfter(string: inout String, char: Character) -> String {

    var newString = ""

    if let charRange = string.range(of: String(char)) {
        newString = string.removeSubrange(charRange.lowerBound..<string.endIndex)
    }
    return newString
}

我收到标题中的错误。为什么会这样?

enter image description here

1 个答案:

答案 0 :(得分:1)

当我尝试打印时,问题就出现了(extInfo.trimBefore(char:“。”)。这返回了()。

当我将其更改为:

extInfo.trimAfter(char: ".")
print(extInfo)

它按预期工作。

mutating func trimBefore(char: Character) {

    if let charRange = self.range(of: String(char)) {
        self.removeSubrange(self.startIndex..<charRange.upperBound)
    }
}

mutating func trimAfter(char: Character) {

    if let charRange = self.range(of: String(char)) {
        self.removeSubrange(charRange.lowerBound..<self.endIndex)
    }
}