Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can somebody give a snippet of "append if not exists" method in swift array?

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

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

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.

like image 245
Chen Li Yong Avatar asked Oct 02 '17 03:10

Chen Li Yong


People also ask

Can array have different data types in Swift?

Swift Array – With Elements of Different TypesIn Swift, we can define an array that can store elements of any type. These are also called Heterogenous Collections. To define an array that can store elements of any type, specify the type of array variable as [Any].

What is the difference between set and array in Swift?

Swift provides three primary collection types, known as arrays, sets, and dictionaries, for storing collections of values. Arrays are ordered collections of values. Sets are unordered collections of unique values. Dictionaries are unordered collections of key-value associations.

How do arrays work in Swift?

Swift arrays are a very common data type used to organize your app's data. You can store multiple elements into an array, such as integers or strings. With arrays, you can do a lot of useful tasks, such as add, remove, or update the elements. You can also neatly loop through the arrays element by element.


1 Answers

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)
        }
    }
}
like image 98
Leo Dabus Avatar answered Sep 28 '22 02:09

Leo Dabus