[SOLVED] How to count how many types in array[Any] – Stack Overflow

Issue

This Content is from Stack Overflow. Question asked by camid

I am new to Swift so im just trying to solve basic problems, but can’t figure out this one.

I am trying to count how many times a String, Int, Double or another class appears. And output the data. Right now i am only outputting the type. This is the code so far:

var myArr = [Any]()

myArr.append("hello")
myArr.append("goodbye")
myArr.append(1)
myArr.append(1.0)
myArr.append(Student())

for item in myArr {
    switch item {
    case let stringy as String :
        print(stringy, type(of: stringy))
    case let inty as Int :
        print(type(of: inty))
    case let doubly as Double :
        print(type(of: doubly))
    case let student as Student :
        print(type(of: student))
    default:
        print("unknown object")
    }
}



Solution

A simple solution is to group the array to a dictionary by the type description

var myArr = [Any]()

myArr.append("hello")
myArr.append("goodbye")
myArr.append(1)
myArr.append(1.0)
myArr.append(Student())

let typeData = Dictionary(grouping: myArr, by: {String(describing:type(of: $0))})

// -> ["Student": [__lldb_expr_9.Student()], "Double": [1.0], "Int": [1], "String": ["hello", "goodbye"]]

and print the result, the key and the number of items in value

for (key, value) in typeData {
    print("\(key): \(value.count)" )
}


This Question was asked in StackOverflow by camid and Answered by vadian It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?