gpt4 book ai didi

swift - 在 Swift 中的条件下删除集合的最后一个元素

转载 作者:搜寻专家 更新时间:2023-11-01 05:49:20 24 4
gpt4 key购买 nike

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

到目前为止我的实现:

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

while true {
if (array.last == " " || array.last == "") {
array.removeLast()
} else {
break
}
}

我想要的输出是

["A", "B", "", "C", "D"]

,但我当前的输出是

["A", "B", "", "C", "D", " ", " "]

while 循环在遇到 ""

后简单地 中断

有什么建议为什么它不接收 ""

最佳答案

我不知道为什么他们有 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]
}
}

"123".dropLast(while: \.isWholeNumber)    // ""
"abc123".dropLast(while: \.isWholeNumber) // "abc"
"123abc".dropLast(while: \.isWholeNumber) // "123abc"

并且扩展 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)...)
}
}

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"]

关于swift - 在 Swift 中的条件下删除集合的最后一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55138253/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com