NeoWang
NeoWang

Reputation: 18513

What is correct parameter type to use that accept tuples in swift?

I am writing a function that accepts an array of anything:

 func getRandomMember(from:[Any]) {

But when I pass it an array of tuples:

 getRandomMember([(1,1), (-1,1), (-1,-1), (1, -1)])

Xcode tells me it is an error:

[(Int, Int)] is not convertable to [Any].

AnyObject doesn't work either. So what type should I use as the parameter type?

Upvotes: 2

Views: 63

Answers (1)

Sweeper
Sweeper

Reputation: 271040

When I test your code in a playground, it works perfectly fine. I think you just forgot to add the argument label from.

getRandomMember(from: [(1,1), (-1,1), (-1,-1), (1, -1)])

However, although the above works, I think using generics here is a better choice here. You can declare your function generically:

func getRandomMemeber<T>(from array: [T]) -> T

This way, you don't need to cast the value returned to the type you want.

Upvotes: 3

Related Questions