Nao Ohta
Nao Ohta

Reputation: 339

A type representing any tuple?

It seems that tuple isn't convertible to 'Any' type. Do you know a type representing any tuple?

func myFunc(x: Any) {
}

myFunc( [12, 34, 56] ) // OK
myFunc( (78, 90, "Hello") ) // error: '((Int, Int, String)) -> ()' is not convertible to '(Any) -> ()'

Upvotes: 3

Views: 90

Answers (3)

Nao Ohta
Nao Ohta

Reputation: 339

I saw SwiftyBeaver's code (thanks). Then I wrote this with their way.

func myFunc(@autoclosure a: () -> Any) {
    let x = a()
}

myFunc( [12, 34, 56] ) // OK
myFunc( (78, 90, "Hello") ) // OK, too

Upvotes: 0

overactor
overactor

Reputation: 1789

If this is a possibility for you, I'd recommend using a generic function instead:

func myFunc<T>(x: T) {
}

myFunc( [12, 34, 56] ) // OK
myFunc( (78, 90, "Hello") ) // Fine too

But it's hard to tell without knowing what exactly you're doing in your function.

Upvotes: 1

Thilo
Thilo

Reputation: 262494

It seems you have to cast it explicitly, but then it works:

func myFunc(x: Any) {
}

myFunc( (78, 90, "Hello") as Any)

I suppose that is necessary as the more common case of passing a tuple to a function is to have the tuple decompose into the separate parameters of the function (as opposed to being a parameter itself).

Upvotes: 1

Related Questions