Home > Back-end >  How to count how many types in array[Any]
How to count how many types in array[Any]

Time:09-19

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

CodePudding user response:

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

CodePudding user response:

For your question, you can make a value storeCount to store value each team it match in each switch case

But the thing is that is not the good way to do that. You can split the array into subarray which each array match a type then you can easily to deal with value later.

Using filter to filter from beginning array each value which match with condition ( here is type given). If right type than get value.

let stringArr = myArr.filter {
    $0 as? String != nil
}
let intArr = myArr.filter {
    $0 as? Int != nil
}
let doubleArr = myArr.filter {
    $0 as? Double != nil
}
let studentArr = myArr.filter {
    $0 as? Student != nil
}

Usage

print("value string: ", stringArr, "; count: ", stringArr.count) // value string:  ["hello", "goodbye"] ; count:  2
print("value int: ", intArr, "; count: ", intArr.count) // value int:  [1] ; count:  1
print("value double: ", doubleArr, "; count: ", doubleArr.count) // value double:  [1.0] ; count:  1
print("value student: ", studentArr, "; count: ", studentArr.count) // value student:  [SelectText.Student] ; count:  1
  • Related