swiftuivisionos

How to Pass Both Int and String to WindowGroup?


I'm working on a SwiftUI project where I need to pass both an Int and a String to a WindowGroup in my app. However, I'm encountering issues with the required conformances for custom data types.

Here's a simplified version of my current code:

import SwiftUI

struct MyData {
    let intValue: Int
    let stringValue: String
}

@main
struct MyApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }

        // How can I pass both an Int and a String here?
        WindowGroup(id: "SecondWindow", for: MyData.self) { data in
            // Content for second window
        }
    }
}

Do I really need add so much boiler plate code just to pass an extra variable?

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

Solution

  • You must conform Codable and Hashable because WindowGroup initialization function requires that. Following the document, the input is (Decodable & Encodable & Hashable).Protocol.

    public init<D, C>(id: String, for type: D.Type, @ViewBuilder content: @escaping (Binding<D?>) -> C) where Content == PresentedWindowContent<D, C>, D : Decodable, D : Encodable, D : Hashable, C : View

    struct MyData: Codable, Hashable {
        let intValue: Int
        let stringValue: String
    }
    

    MyData just contains primative types such as Int, String, so you can avoid those Codable and Hashable implementations.