【问题标题】:swift Generics with protocol带有协议的快速泛型
【发布时间】:2023-01-12 17:47:44
【问题描述】:

我用泛型创建了一个函数

func sorted<T: MyProtocol>(array: [T]) -> [T] { ... }

并试图打电话

let array: [MyProtocol] = [...]
let sortedArray = sorted(array: array)

但是得到错误

Type 'any MyProtocol' cannot conform to 'MyProtocol'

我知道变量array是一个盒子,可以包含任何符合MyProtocol的东西。但是我该如何解决这个问题呢?我需要对任何类型的MyProtocol进行排序

试过这样的事情,但没有工作

func sorted<T: any MyProtocol>(array: [T]) -> [T] { ... }

【问题讨论】:

    标签: swift generics


    【解决方案1】:

    错误消息表明数组变量中元素的类型 anyProtocol 与排序函数的通用约束 MyProtocol 中指定的类型不同。

    在 Swift 中,any 是所有类型都遵循的协议。所以 any MyProtocol 是一种同时符合 any 和 MyProtocol 协议的类型。

    要修复此错误,您可以将数组变量的类型更改为 [MyProtocol] 或将排序函数的约束更改为 T: any MyProtocol。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-10
      • 2023-03-14
      • 1970-01-01
      • 2020-01-22
      • 2017-12-25
      • 1970-01-01
      相关资源
      最近更新 更多