Home > Software design >  Swift method needs to sort a polymorphic collection of UInt32
Swift method needs to sort a polymorphic collection of UInt32

Time:04-30

Confused (and a little frustrated) with Swift5 at the moment.

I have a method:

func oidsMany(_ oids:Array<UInt32>) -> MCCommandBuilder {
    let sorted_oids:[UInt32] = oids.sorted()
    ...
}

Discovered I have a case where I want to pass a Set to this method just as well. Either way, I'm going to sort an Array or a Set to an Array right away.

Waded through the many many many protocols that both Set and Array conform to, noticed that they both conform to [Sequence][1] and that Sequence responds to sorted. Perfect.

But when I change the above to:

func oidsMany(_ Sequence<UInt32>) -> MCCommandBuilder {
    let sorted_oids:[UInt32] = oids.sorted()
    ...
}

I get the following error hints:

Cannot specialize non-generic type 'Sequence'
Member 'sorted' cannot be used on value of protocol type 'Sequence'; use a generic constraint instead

What's the right way to approach this? I could just add a second oidsMany(_ Set...) that casts its arg as an array and recalls. But I feel like I'm missing something fundamental here. My experience from other languages is not mapping over well here.

CodePudding user response:

You can as the error message suggest use it as a generic constraint instead

func oidsMany2<Sortable: Sequence>(_ oids: Sortable) -> MCCommandBuilder where Sortable.Element: Comparable {
    let sorted_oids:[Sortable.Element] = oids.sorted()
    //...
}

if you only want to accept collections where the element is UInt32 you can change the where condition to

where Sortable.Element == UInt32 
  • Related