Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot pass any array type to a function which takes [Any] as parameter

Tags:

arrays

swift

I have an array of type [String]

let names = ["Joffrey", "Cersei", "Mountain", "Hound"]

I have a function which takes an array of [Any] type.

func printItems(items: [Any]){
    for item in items {
        print(item)
    }
}

Now when I call the function with names as parameters,

printItems(names)

I get an error Cannot invoke 'printItems' with an argument list of type '([String])'.

Any is just a typealias for a protocol which all types implicitly conform to.

Thoughts?

like image 593
Ramsundar Shandilya Avatar asked Oct 20 '22 06:10

Ramsundar Shandilya


1 Answers

This is a surprising limitation of Swift. You can't cast an array to type [Any] so you can't pass it to a function taking type [Any]. You can use map to cast each item of the array:

printItems(names.map {$0 as Any})

But, the right way to do this in Swift is to use Generics:

func printItems<T>(items: [T]) {
    for item in items {
        print(item)
    }
}

let names = ["Joffrey", "Cersei", "Mountain", "Hound"]
let numbers = [3.1416, 2.71818, 1.4142, 1.618034]

printItems(names)    // This now works
printItems(numbers)  // This works too
like image 185
vacawama Avatar answered Oct 21 '22 23:10

vacawama