Can someone give a snippet of the add if it doesn't exist method in a fast array?

Since I often use this procedure, can someone create a Swift array extension method that will determine if the data to be added already exists, then it is not added? I know that these are just a few of these codes:

var arr = [Int]()
for element in inputArr {
    if !arr.contains(element) { arr.append(element); }
}

becomes:

var arr = [Int]()
for element in inputArr { arr.appendUnique(element); }

Or:

var arr = [String]()
for element in inputArr {
    if !arr.contains(element) { arr.append(element); }
}

becomes:

var arr = [String]()
for element in inputArr { arr.appendUnique(element); }

The same method for different types of elements. Honestly, from this simple code I also want to learn how to extend with Collectionvariable types. I admire how Array methods can have different types of parameters when an object was initialized with different types of parameters. An array and a dictionary are two things that I still do not understand how to expand them correctly. Thank you

+9
3

RangeReplaceableCollection, Equatable . Bool , . :

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

( , ).

extension RangeReplaceableCollection where Element: Equatable
{
    mutating func prependUnique(_ element: Element) {
        if let index = firstIndex(of: element) {
            remove(at: index)
        }
        insert(element, at: startIndex)
    }
}
0

API, , , arr.removeAll().

0

Source: https://habr.com/ru/post/1686780/


All Articles