Viktor Kucera
Viktor Kucera

Reputation: 6335

Call function with empty variadic param

I have a function with one variadic param (tuple) like this:

func conditions<T>(conditions: ([String : T], LogicalOperator)...) -> [AnyObject]?

Is there any way how to call it without that param? Somehow pass an empty array of variadic params? I just want to be able to support an option when there are no conditions at all.

Upvotes: 2

Views: 708

Answers (2)

sunshinejr
sunshinejr

Reputation: 4854

You can do it, but not as a generic function. Why? Because it can't infer the type, so the compiler doesn't know what T is, even tho your tuple will be optional. So code below in theory would work, but the execution will fall:

struct Test<T> {
    func conditions<T>(conditions: ([String : T], String)?...) -> [AnyObject]? {
        return nil
    }
}

var t = Test<Int>()
t.conditions() // Error infering type

However, this one does work (if it does satisfy your needs):

struct Test<T> {
    typealias testAlias = ([String : T], String)
    func conditions(conditions: testAlias...) -> [AnyObject]? {
        return nil
    }
}

var t = Test<Int>()
t.conditions()

Upvotes: 1

72A12F4E
72A12F4E

Reputation: 1754

You can accomplish what you want with function overloading.

You could overload your function definition to accept no arguments...

  • func conditions() -> [AnyObject]?

or, you could overload it to accept an array of your type...

  • func conditions<T>(conditions: [([String : T], LogicalOperator)]) -> [AnyObject]?

or you could make it accept optional values and pass nil.

  • func conditions<T>(conditions: ([String : T], LogicalOperator)?...) -> [AnyObject]?

Upvotes: 1

Related Questions