Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In argument type '[ItemA]', 'ItemA' does not conform to expected type 'Sortable'

Tags:

generics

swift

I have run into a weird error using Swift, but I can't seem to find the issue. The error should not be thrown I think, and I have verified this issue with the code below in a playground.

protocol Sortable {
}

protocol ItemA: Sortable {
}

func sortItems<T: Sortable>(items: [T]) -> [T] {
    // do the sorting here
    return items
}

let list: [ItemA] = []

sortItems(items: list)
like image 902
vrwim Avatar asked Aug 06 '18 09:08

vrwim


1 Answers

You cannot pass another protocol that inherits from the constrained protocol in current Swift version (4.1).

If you make ItemA a struct, a class or an enum, it will work.

OR

If you would change your sortItems implementation to simply take Sortable as an argument like this, then you can use another protocol that inherits from Sortable, but you will lose the information about the type.

func sortItems(items: [Sortable]) -> [Sortable] {
    // do the sorting here
    return items
}

You can find more information on this issue here.

like image 92
Zdeněk Topič Avatar answered Oct 01 '22 01:10

Zdeněk Topič