有人可以提供“如果不存在则追加”代码段吗?快速数组中的方法? [英] Can somebody give a snippet of "append if not exists" method in swift array?
问题描述
因为我经常使用此例程,所以有人可以创建Swift数组的扩展方法来检测是否要添加的数据已经存在,然后是否要添加?我知道这只是几个代码的问题:
Because I use this routine a lot, can somebody create an extension method of Swift array which will detect whether if the data that is going to be appended already exists, then it's not appended? I know that it's only a matter of few code like this:
var arr = [Int]()
for element in inputArr {
if !arr.contains(element) { arr.append(element); }
}
成为:
var arr = [Int]()
for element in inputArr { arr.appendUnique(element); }
或:
var arr = [String]()
for element in inputArr {
if !arr.contains(element) { arr.append(element); }
}
成为:
var arr = [String]()
for element in inputArr { arr.appendUnique(element); }
不同元素类型的相同方法。坦率地说,从这个简单的代码中,我还想学习如何使用变量类型扩展 Collection
。它使我着迷,无论何时使用不同的参数类型初始化对象时,Array的方法如何具有不同的参数类型。数组和字典是我仍然无法正确扩展它们的两件事。谢谢。
Same method for different element types. Frankly, from this simple code, I also want to learn on how to extend the Collection
with variable types. It fascinates me how Array's methods can have different parameter types whenever the object was initialized with different parameter types. Array and Dictionary are two things that I still don't get how to extend them properly. Thanks.
推荐答案
您可以扩展 RangeReplaceableCollection
,将其元素限制为 Equatable
并声明您的方法为变异。如果要返回Bool以防追加成功,还可以使结果可丢弃。您的扩展程序应如下所示:
You can extend RangeReplaceableCollection
, constrain its elements to Equatable
and declare your method as mutating. If you want to return Bool in case the appends succeeds you can also make the result discardable. Your extension should look like this:
extension RangeReplaceableCollection where Element: Equatable {
@discardableResult
mutating func appendIfNotContains(_ element: Element) -> (appended: Bool, memberAfterAppend: Element) {
if let index = firstIndex(of: element) {
return (false, self[index])
} else {
append(element)
return (true, element)
}
}
}
这篇关于有人可以提供“如果不存在则追加”代码段吗?快速数组中的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!