Swift 方法需要对 UInt32 的多态集合进行排序
Swift method needs to sort a polymorphic collection of UInt32
目前对 Swift5 感到困惑(并且有点沮丧)。
我有一个方法:
func oidsMany(_ oids:Array<UInt32>) -> MCCommandBuilder {
let sorted_oids:[UInt32] = oids.sorted()
...
}
发现我也想将 Set
传递给此方法。无论哪种方式,我都会立即对 Array 或 Set 进行排序。
浏览了 Set 和 Array 都符合的许多协议,注意到它们都符合 [Sequence][1]
并且 Sequence 响应 sorted
。完美。
但是当我把上面的改成:
func oidsMany(_ Sequence<UInt32>) -> MCCommandBuilder {
let sorted_oids:[UInt32] = oids.sorted()
...
}
我得到以下错误提示:
Cannot specialize non-generic type 'Sequence'
Member 'sorted' cannot be used on value of protocol type 'Sequence'; use a generic constraint instead
解决这个问题的正确方法是什么?我可以添加第二个 oidsMany(_ Set...) 将其 arg 转换为数组并调用。但我觉得我在这里缺少一些基本的东西。我在其他语言方面的经验并没有很好地反映在这里。
您可以按照错误消息的建议将其用作通用约束
func oidsMany2<Sortable: Sequence>(_ oids: Sortable) -> MCCommandBuilder where Sortable.Element: Comparable {
let sorted_oids:[Sortable.Element] = oids.sorted()
//...
}
如果您只想接受元素为 UInt32 的集合,您可以将 where
条件更改为
where Sortable.Element == UInt32
目前对 Swift5 感到困惑(并且有点沮丧)。
我有一个方法:
func oidsMany(_ oids:Array<UInt32>) -> MCCommandBuilder {
let sorted_oids:[UInt32] = oids.sorted()
...
}
发现我也想将 Set
传递给此方法。无论哪种方式,我都会立即对 Array 或 Set 进行排序。
浏览了 Set 和 Array 都符合的许多协议,注意到它们都符合 [Sequence][1]
并且 Sequence 响应 sorted
。完美。
但是当我把上面的改成:
func oidsMany(_ Sequence<UInt32>) -> MCCommandBuilder {
let sorted_oids:[UInt32] = oids.sorted()
...
}
我得到以下错误提示:
Cannot specialize non-generic type 'Sequence'
Member 'sorted' cannot be used on value of protocol type 'Sequence'; use a generic constraint instead
解决这个问题的正确方法是什么?我可以添加第二个 oidsMany(_ Set...) 将其 arg 转换为数组并调用。但我觉得我在这里缺少一些基本的东西。我在其他语言方面的经验并没有很好地反映在这里。
您可以按照错误消息的建议将其用作通用约束
func oidsMany2<Sortable: Sequence>(_ oids: Sortable) -> MCCommandBuilder where Sortable.Element: Comparable {
let sorted_oids:[Sortable.Element] = oids.sorted()
//...
}
如果您只想接受元素为 UInt32 的集合,您可以将 where
条件更改为
where Sortable.Element == UInt32