Swift function that takes a specific protocol array can't take an array of types conforming to such protocol
Originator: | oscar | ||
Number: | rdar://23499056 | Date Originated: | 11/11/2015 |
Status: | Duplicate of 18596002 | Resolved: | |
Product: | Developer Tools | Product Version: | Xcode 7.1.1 |
Classification: | Reproducible: | Always |
Summary: Having a protocol A and a struct X conforming to A, if a function takes an array of A and you pass an array of instances of X, the compiler throws an error: Cannot convert value of type `[X]` to expected argument type `[A]` Steps to Reproduce: 1. Define a simple protocol protocol A { var a: String { get set } } 2. Define a struct that conforms to that protocol struct X: A { var a: String } 3. Define a function that takes an array of As func takesAs(aas: [A]) { // Something } 4 . Create an array of Xs let letters = ["A", "B", "C", "D"] let xs = letters.map { X(a: $0) } // xs is of type [X] takesAs(xs) // Cannot convert value of type `[X]` to expected argument type `[A]` let xs2: [A] = letters.map { X(a: $0) } // xs2 is casted to type [A] takesAs(xs2) // Works as expected Expected Results: The function expecting an array of protocols accepts an array of types conforming to that protocol as parameter. Actual Results: The function expecting an array of protocols doesn't accept an array of types conforming to that protocol as parameter and errors with "Cannot convert value of type `[X]` to expected argument type `[A]`" Version: Xcode 7.1.1, Swift 2.1
Comments
Please note: Reports posted here will not necessarily be seen by Apple. All problems should be submitted at bugreport.apple.com before they are posted here. Please only post information for Radars that you have filed yourself, and please do not include Apple confidential information in your posts. Thank you!
Actually, you just have to type it to make it work.
let xs: [A] = letters.map { X(a: $0) }
Which makes sense.
I have to confirm this.