class 和 struct 的典型使用示例
时间: 2025-06-06 19:54:34
(部分内容来自网络,其真实性存疑,为了避免对您造成误导,请谨慎甄别。)
以下是 class 和 struct 的典型使用示例,涵盖不同场景:
1. struct 示例:轻量级数据模型
swift
Copy Code
// 定义值类型的数据模型
struct User {
var id: UUID
var name: String
var email: String
// 计算属性
var displayName: String {
"$name) ($email))"
}
}
// 使用
var user1 = User(id: UUID(), name: "Alice", email: "alice@example.com")
let user2 = user1 // 独立副本
user1.name = "Bob"
print(user2.name) // 输出 "Alice"(值类型互不影响)
2. class 示例:共享状态的服务类
swift
Copy Code
// 定义引用类型的网络服务
class NetworkManager {
static let shared = NetworkManager() // 单例模式
private init() {}
func fetchData(completion: @escaping (Result<Data, Error>) -> Void) {
URLSession.shared.dataTask(with: URL(string: "https://api.example.com")!) { data, _, error in
if let error = error {
completion(.failure(error))
} else if let data = data {
completion(.success(data))
}
}.resume()
}
}
// 使用
NetworkManager.shared.fetchData { result in
switch result {
case .success(let data): print("数据获取成功")
case .failure(let error): print("错误: $error)")
}
}
3. struct 示例:不可变配置项
swift
Copy Code
// 定义不可变配置
struct AppConfig {
let apiBaseURL: String
let maxRetryCount: Int
let isDebugMode: Bool
// 默认配置
static let production = AppConfig(
apiBaseURL: "https://api.example.com",
maxRetryCount: 3,
isDebugMode: false
)
}
// 使用
let config = AppConfig.production
print(config.apiBaseURL) // 输出 "https://api.example.com"
4. class 示例:视图控制器(UIKit)
swift
Copy Code
// 定义视图控制器(需引用语义)
class ProfileViewController: UIViewController {
private let user: User
init(user: User) {
self.user = user
super.init(nibName: nil, bundle: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
}
private func setupUI() {
let label = UILabel()
label.text = "欢迎, $user.name)"
view.addSubview(label)
// 布局代码...
}
}
5. struct 与协议结合
swift
Copy Code
// 定义协议
protocol Drawable {
func draw() -> String
}
// 结构体实现协议
struct Circle: Drawable {
var radius: Double
func draw() -> String {
"绘制圆形,半径: $radius)"
}
}
// 使用
let shapes: [Drawable] = [Circle(radius: 5.0)]
print(shapes[0].draw()) // 输出 "绘制圆形,半径: 5.0"
关键选择建议
用 struct:数据模型、配置项、简单状态(优先选择)。
用 class:需要共享状态、继承或与 Objective-C 交互时(如 UIKit 控件)。