gpt4 book ai didi

swift - 改变字符串扩展导致巨大的 CPU 影响

转载 作者:行者123 更新时间:2023-11-28 08:25:34 35 4
gpt4 key购买 nike

我为 String 类创建了一个小扩展,以便方便地从中删除字符。这是它的样子:

mutating func drop(characters chars: [String]) {
for c in chars {
self = self.replacingOccurrences(of: c, with: "")
}
}

用法:

//string = ""Test"" (contains quotes), should be "Test" (w/ quotes)
string.drop(characters: ["\""])

现在,当我在字符串上调用此函数时,CPU 会飙升导致应用程序最终崩溃。

有什么想法吗?
谢谢!


更新

我意识到以下代码也会对 CPU 产生巨大影响,因此这显然不是我的扩展的问题,而是其他问题:

string = string.replacingOccurrences(of: "\"", with: "")

更新 #2/解决方案

我发现了问题。我在一个 while 循环中执行上述语句,一旦 superString 中的字符串不再存在,该循环就会结束。为此,我通过 replacingOccurrencessuperString 中删除了 string。我意识到,after 执行语句 string 显然不像以前在 superString 中出现的那样。
长话短说:我必须执行语句 aftersuperString 中删除 string 否则 while 循环将永远不会结束,这会导致 CPU 影响 &崩溃。

尽管如此,还是感谢您提供帮助!

最佳答案

避免多次改变字符串(这会降低性能)的建议是像这样重写您的函数:

mutating func drop(charactersIn string: String) {
self = String(
self.characters.filter { !string.characters.contains($0) }
)
}

// And then for example:
string.drop(charactersIn: "\"tT")

关于swift - 改变字符串扩展导致巨大的 CPU 影响,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40128344/

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