You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift中如何统计Any类型数组内各数据类型的出现次数

Swift数组类型出现次数统计方案

要统计数组中各类型的出现次数,你可以用字典记录每种类型的计数,遍历数组时更新计数,最后输出统计结果。以下是修改后的完整代码:

// 先定义Student类(原代码中用到的自定义类)
class Student {}

var myArr = [Any]()

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

// 存储类型名称与对应出现次数的字典
var typeCount: [String: Int] = [:]

// 遍历数组统计次数
for item in myArr {
    let typeName = String(describing: type(of: item))
    // 更新计数:首次出现则初始化为1,已存在则计数+1
    typeCount[typeName] = (typeCount[typeName] ?? 0) + 1
    
    // 保留你原有的元素类型输出(可选,不需要可删除)
    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")
    }
}

// 输出最终统计结果
print("\n类型统计结果:")
for (type, count) in typeCount {
    print("\(type) 出现了 \(count) 次")
}

代码说明:

  • 计数字典:typeCount的键是类型名称字符串,值为该类型在数组中的出现次数
  • 获取类型名称:String(describing: type(of: item))将元素类型转换为可读的字符串格式
  • 计数更新逻辑:(typeCount[typeName] ?? 0) + 1处理首次出现的类型(默认计数取0,加1后变为1),已存在的类型则直接在原有计数上加1
  • 可选输出:如果不需要逐个打印元素的类型信息,可以删除代码中的switch块,只保留统计逻辑

运行代码后,会先输出每个元素的类型信息,最后输出类似如下的统计结果:

类型统计结果:
String 出现了 2 次
Int 出现了 1 次
Double 出现了 1 次
Student 出现了 1 次

内容的提问来源于stack exchange,提问作者camid

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 21:30:51