Swift 编程中的枚举与数据类型处理
在 Swift 编程中,处理不同类型的数据是一项常见的任务。本文将深入探讨如何使用数组存储多种类型的数据,以及枚举在数据建模中的应用,同时介绍代数数据类型和安全使用字符串枚举的相关知识。
1. 数组中存储多种类型数据
在 Swift 中,数组通常希望存储相同类型的数据。但有时需要存储多种类型的数据,这时可以使用 Any 类型。
1.1 使用 Any 类型
let arr: [Any] = [Date(), "Why was six afraid of seven?", "Because...", 789]
由于在编译时不知道 Any 具体代表什么类型,所以需要在运行时检查 Any 类型。可以使用 switch 语句进行模式匹配:
let arr: [Any] = [Date(), "Why was six afraid of seven?", "Because...", 789]
for element: Any in arr {
// element is "Any" type
switch element {
case let stringValue as String:
print("received a string: \(stringValue
超级会员免费看
订阅专栏 解锁全文
20

被折叠的 条评论
为什么被折叠?



