Search code examples
swiftswiftdata

How to pass variadic arguments in ModelContainer(for:) in other init?


I want to initialize my class with initializer:

init(for forTypes: any PersistentModel.Type...) {
    container = try? ModelContainer(for: forTypes)
}

But I got an error:

Cannot pass array of type 'any PersistentModel.Type...' as variadic arguments of type 'any PersistentModel.Type'

How can I solve this? I've tried passing without any, that gets me to another error:

Use of protocol 'PersistentModel' as a type must be written 'any PersistentModel'

Solution

  • The problem is that you can't pass on a variadic parameter, once inside the function (init) it's an array and there's no init for ModelContainer that takes an array of PersistentModel.

    One workaround is to use an init that takes a Schema

    init(for types: any PersistentModel.Type...) throws {
        container = try ModelContainer(for: Schema(types))
    }