Swift 中的条件删除集合的最后一个元素

Koh*_*Koh 5 swift

我试图从字符串数组的后面删除""& ,直到最后一项包含一些文本,但我的实现没有拾取." "" "

到目前为止我的实现:

var array = ["A", "B", "", "C", "D", " ", " ", ""]

while true {
    if (array.last == " " || array.last == "") {
        array.removeLast()
    } else {
        break
    }
}
Run Code Online (Sandbox Code Playgroud)

我想要的输出是

["A", "B", "", "C", "D"]
Run Code Online (Sandbox Code Playgroud)

,但我当前的输出是

["A", "B", "", "C", "D", " ", " "]
Run Code Online (Sandbox Code Playgroud)

,其中在遇到后while立即循环breaks" "

有什么建议为什么它不接听吗" "

Leo*_*bus 5

我不知道为什么他们有drop(while:)但没有实施dropLast(while:)。下面的实现适用于任何集合:

extension Collection {
    func dropLast(while predicate: (Element) throws -> Bool) rethrows -> SubSequence {
        guard let index = try indices.reversed().first(where: { try !predicate(self[$0]) }) else {
            return self[startIndex..<startIndex]
        }
        return self[...index]
    }
}
Run Code Online (Sandbox Code Playgroud)
"123".dropLast(while: \.isWholeNumber)    // ""
"abc123".dropLast(while: \.isWholeNumber) // "abc"
"123abc".dropLast(while: \.isWholeNumber) // "123abc"
Run Code Online (Sandbox Code Playgroud)

并扩展 RangeReplaceableCollection 我们也可以remove(while:)实现:removeLast(while:)

extension RangeReplaceableCollection {
     mutating func remove(while predicate: (Element) throws -> Bool) rethrows {
        guard let index = try indices.first(where: { try !predicate(self[$0]) }) else {
            removeAll()
            return
        }
        removeSubrange(..<index)
    }
    mutating func removeLast(while predicate: (Element) throws -> Bool) rethrows {
        guard let index = try indices.reversed().first(where: { try !predicate(self[$0]) }) else {
            removeAll()
            return
        }
        removeSubrange(self.index(after: index)...)
    }
}
Run Code Online (Sandbox Code Playgroud)
var string = "abc123"
string.removeLast(while: \.isWholeNumber)
string  // "abc"

var string2 = "abc123"
string2.remove(while: \.isLetter)
string2 // "123"

var array = ["A", "B", "", "C", "D", " ", " ", ""]
array.removeLast { $0 == "" || $0 == " " }
array  // ["A", "B", "", "C", "D"]
Run Code Online (Sandbox Code Playgroud)


Dar*_*ust 4

解决此问题的一种方法是反转集合(这是延迟完成的)并删除不需要的项目,直到遇到想要的项目。之后,再次反转集合。

let array = ["A", "B", "", "C", "D", " ", " ", ""]

let filtered = array.reversed().drop(while: {
    $0.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
}).reversed() as [String]

print(filtered) // "["A", "B", "", "C", "D"]\n"
Run Code Online (Sandbox Code Playgroud)

" "请注意,如果不是普通空格,例如不间断空格(Unicode 检查点 U+00A0),则检查可能会失败。这可能是您首先遇到的问题。因此,修剪字符串(仅删除开头和结尾的字符)并检查结果是否为空字符串。

  • 如果您决定反转数组,您可能需要使用“drop(while:)”。“filter”在这里并不是一个好的选择。 (3认同)