Removing Specific Type from an Array in Swift

Valsamis Elmaliotis
2 min readOct 1, 2019

--

Photo by Taras Shypka on Unsplash

Imagine that you have an array like this:

let array: [Any] = [nick, john, nick, “String”, 3]

and you want to remove all elements of a specific Type! What will we do?

Let’s create an example…

class Nick {}struct John {}let nick = Nick()let john = John()let array: [Any] = [nick, john, nick, "String", 3, "AnotherString"]print(array)

In this example we have a Class Nick and a Struct John.

Finally our array contains 2 Nick objects, 1 John, 2 Strings and 1 Integer.

The print result is:

[__lldb_expr_12.Nick, __lldb_expr_12.John(), __lldb_expr_12.Nick, "String", 3, "AnotherString"]

Let’s say we want to remove all nick objects form this array.

Create a helper function:

func removeType(formArray array: [Any], ofType type: Any.Type) -> [Any] {    //1    let filteredArray = array.filter { item in
//2
let mirror = Mirror(reflecting: item)
//3
return mirror.subjectType != type }
//4
return filteredArray}

Our function takes as argument the array we need to modify and the type we want to remove. Finally return the modified array.

To achieve our result we need to filter the original array. (1)

In the filtering block we want to mirror the active element (2) and get it’s subjectType (3). If the subjectType is different than the type we want to remove, we keep the item.

Finally we return the filtered array (4)

Let’s call this function to remove all Nick objects

var filteredArray = removeType(formArray: array, ofType: Nick.self)print(filteredArray)

We pass as type argument the Type of Nick object.

The print result is:

[__lldb_expr_16.John(), "String", 3, "AnotherString"]

As we can see all Nick objects are removed.

If we wanted to remove all Strings we could use:

var filteredArray = removeType(formArray: array, ofType: String.self)print(filteredArray)

The print result is:

[__lldb_expr_1.Nick, __lldb_expr_1.John(), __lldb_expr_1.Nick, 3]

See you next time!

--

--