5

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?

4
  • thumbs up for names in array :) Jul 29, 2015 at 10:04
  • Can't speak for swift, but in most languages this could be a problem because printItems might take that array of Any and change one of the items to - well - anything it wanted to (something other than a string). But the caller thinks that they have an array of Strings so may have issues once printItems has finished. Does that apply to swift? Jul 29, 2015 at 10:05
  • What if you change type of your names array to [Any] Jul 29, 2015 at 10:12
  • @Damien_The_Unbeliever: no, this does not apply here because in Swift the Array is a Struct. This means it is copied when it is assigned to another variable then the problem described by you (that exists in other languages such as Java) does not happen here. Jul 29, 2015 at 10:44

3 Answers 3

2

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
3
  • 1
    👍for the generic recommendation Jul 29, 2015 at 10:45
  • Thanks for the Generics answer. But I'm taking a session on Generics. I wanted to know why this fails. I should be prepared with an answer for it. Jul 31, 2015 at 3:38
  • @AirspeedVelocity's answer tells you why this fails. You should up vote and accept his answer.
    – vacawama
    Jul 31, 2015 at 9:24
1

While every type conforms Any, this is not the same as it being a universal implicit superclass that all types inherit from.

When you cast a type to a protocol, you create a new value with a different structure. So for a string to be of type Any, it needs to be physically transformed from the String representation:

sizeof(String) // 24 bytes (on 64-bit, anyway)

to the Any representation:

sizeof(Any) // 32 bytes, includes some meta data 
            // about what the type really is

Since value types are held directly in the array, the array would be a very different shape so under the hood the compiler would have to do the equivalent of this:

names.map { $0 as Any } // create a new array, with the Any versions

Swift could perhaps automate this process for you (it does if you pass a single variable into a function that takes Any). But personally I’m glad it doesn’t, I’d rather this be more explicit – suppose your array was huge, this would be a lot of processing happening implicitly under the hood.

This is different from when you have an array of reference types, all of which are pointers to the actual data and so all the same size, and which need no transformation when upcasting:

class C  { }
class D: C { }

let d = D()
let c: C = d
unsafeBitCast(d, UnsafePointer<Void>.self)  // these value will
unsafeBitCast(c, UnsafePointer<Void>.self)  // be the same

So saying “this array of [D] is really an array of [C]” is just a matter of the compiler agreeing the types can be substituted, no data transformation needs to take place:

// so this works fine, 
// no runtime transformation needed:
func f(cs: [C]) { }
let ds = [D(),D()]
f(ds)

But protocols still are different from superclass references when used with classes:

protocol P { }
extension C: P { }

sizeofValue(C())       // 8 bytes (just a pointer)
sizeofValue(C() as P)  // 40 bytes

func g(ps: [P]) { }
g(ds)  // won’t compile, needs transformation
4
  • 👍for the explanation of the inner workings of arrays
    – vacawama
    Jul 29, 2015 at 10:51
  • The second paragraph is misleading. Any reference type to be of type Any also needs physical transformation, you know?
    – rintaro
    Jul 29, 2015 at 10:53
  • 2
    @rintaro good point, will reword – my point was more that Swift works differently to, say, Java, where Object is the universal subclass. Jul 29, 2015 at 10:58
  • Duh meant superclass. Jul 29, 2015 at 11:05
0

You need to explicitly put in your let declaration that you are declaring an Any array and not a specific type array.

With your current declaration, Swift will evaluate it to [String] array. and not as [Any] array.

To fix your problem just do the following:

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

If you want to retain your let declaration, use AnyObject in your printItems function and it will be accepted by Swift.

func printItems(items: [AnyObject]){
    for item in items {
        print(item)
    }
}
1
  • "If you want to retain your let declaration, use AnyObject in your printItems function and it will be accepted by Swift.” This is a little misleading. What is happening here is that Swift’s auto-bridging is kicking in and converting the entire array to NSString objects. This only works with strings, not arbitrary types, and isn’t a general solution. Note also, this only works if Foundation has been imported. Jul 29, 2015 at 10:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.