有人可以给出“如果不存在则追加"的片段吗?swift数组中的方法? [英] Can somebody give a snippet of "append if not exists" method in swift array?

查看:25
本文介绍了有人可以给出“如果不存在则追加"的片段吗?swift数组中的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因为我经常使用这个例程,有人可以创建一个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 的方法如何可以具有不同的参数类型,这让我着迷.Array 和 Dictionary 是我仍然不知道如何正确扩展它们的两件事.谢谢.

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)
        }
    }
}

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆