有人可以给出“如果不存在则追加"的片段吗?快速数组中的方法?

Can somebody give a snippet of quot;append if not existsquot; 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 并将您的方法声明为 mutating.如果您想在追加成功的情况下返回 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)
        }
    }
}

这篇关于有人可以给出“如果不存在则追加"的片段吗?快速数组中的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:有人可以给出“如果不存在则追加"的片段吗?快速数组中的方法?

基础教程推荐