Search code examples
swiftprotocolsswift5variadic

Swift Protocol with Variadic property


I'm trying to create Swift Protocol with Variadic property. According to the docs, it's possible to do it in a function:

func arithmeticMean(_ numbers: Double...) -> Double {
    var total: Double = 0
    for number in numbers {
        total += number
    }
    return total / Double(numbers.count)
}
arithmeticMean(1, 2, 3, 4, 5)

But trying to create Variadic parameter inside a protocol like follows:

struct ProductModel {
    
}

protocol SubscriptionModel {
    var products: ProductModel... { get set }
}

Results in this error: enter image description here

Is it not possible to create a Variadic property within a Protocol?


Solution

  • Is it not possible to create a Variadic property within a Protocol?

    It is not possible, but this is just one reflection of a larger fact, namely, that a variadic is not a type. You are trying here to say products is of type Variadic ProductModel. But there is no such type. No variable ever can be declared as being of that type; it isn't just protocols.

    The only place variadic notation may appear is as a parameter type in an actual func declaration, but then it is just a notation, not a type. It is a way of saying that the function can take a series of the actual type (Double, in your example from the docs).

    So, if your protocol wants to declare a method with a parameter that's a variadic, fine. But the idea of a variable of variadic type is meaningless.

    So just declare that the type of your variable is [ProductModel]. That is how you say "some unknown number of ProductModel objects". And that's all that variadic notation means anyway, really, since the parameter is received inside the function body as an array.