如何向SwiftUI的WindowGroup同时传递Int与String类型数据?
SwiftUI WindowGroup传递多类型数据:简化自定义类型的协议适配
开发SwiftUI项目时,需要向WindowGroup同时传递Int和String类型的数据,但在自定义数据类型的协议适配时遇到了困惑。
当前简化代码如下:
import SwiftUI struct MyData { let intValue: Int let stringValue: String } @main struct MyApp: App { var body: some Scene { WindowGroup { ContentView() } // 如何在这里同时传递Int和String? WindowGroup(id: "SecondWindow", for: MyData.self) { data in // 第二个窗口的内容 } } }
是否真的需要编写大量模板代码,仅仅为了多传递一个变量?比如下面这段手动实现Decodable和Hashable的代码:
struct MyData: Decodable, Hashable { let intValue: Int let stringValue: String init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) intValue = try container.decode(Int.self, forKey: .intValue) stringValue = try container.decode(String.self, forKey: .stringValue) } enum CodingKeys: String, CodingKey { case intValue case stringValue } func hash(into hasher: inout Hasher) { hasher.combine(intValue) hasher.combine(stringValue) } static func == (lhs: MyData, rhs: MyData) -> Bool { return lhs.intValue == rhs.intValue && lhs.stringValue == rhs.stringValue } }
答案:完全不需要写这些模板代码
Swift支持自动合成Decodable和Hashable的实现,只要你的自定义类型满足以下条件:
- 所有存储属性都遵循对应的协议(比如
Int和String本身就实现了Decodable和Hashable) - 没有自定义的初始化方法(除非你明确指定了符合
Decodable要求的初始化器)
所以只需要这样写即可:
struct MyData: Decodable, Hashable { let intValue: Int let stringValue: String }
Swift会自动帮你生成:
CodingKeys枚举init(from decoder: Decoder)方法hash(into:)方法==运算符重载
这样既满足了WindowGroup对数据类型的要求(WindowGroup的for参数需要符合WindowSceneActivatable协议,该协议继承自Decodable & Hashable),又避免了冗余的模板代码。
内容的提问来源于stack exchange,提问作者János
相关产品推荐
相关产品推荐

