swift - 通用协议属性声明
问题描述
假设我有一个关联类型 T 的协议
protocol Helper{
associatedtype T
func help(_ item: T)
}
在一个类中,我想声明一个属性
class Manager<T>{
let item: T?
let helper: Helper<T>
//Error: Cannot specialize non-generic type 'Helper'
let anotherHelper: Helper
//Error: Protocol 'Helper' can only be used as a generic constraint because it has Self or associated type requirements
}
如何声明和使用 helper 属性,使其强制符合 Helper 协议的类的类型?
我敢肯定,很多具有 Java/C# 或其他类似语言背景的人在尝试做类似的事情时都会遇到困难
解决方案
在这种特殊情况下,您T
可以Manager<T>
改为Helper
:
class Manager<T> where T : Helper {
let item: T.T?
let helper: T
init(helper: T) {
self.helper = helper
item = nil
}
}
如果你想要一个Helper<Int>
,你做:
class IntHelper : Helper {
typealias T = Int
// ...
}
然后使用Manager<IntHelper>
.
推荐阅读
- python - 试图从雅虎股票数据中打印第一个高值,得到“基于非整数索引的索引只能有非整数索引器”
- r - 用 ggplot 绘制不相似的数据
- javascript - 将 JSON 数据提取到表中
- python - 在 Ubuntu 上安装 OpenCV 时出现“致命错误:Eigen/Core:没有这样的文件或目录”
- c# - 在 Syncfusion 的 pdf 查看器中包装 cshtml 的内容
- javascript - 如何更改大屏幕上的菜单对齐方式?
- javascript - JavaScript 和 HTML:事件侦听器未按预期生成文本警报;ReferenceError:未定义按钮
- mysql - MySQL 是否为主键创建额外的索引或使用数据本身作为“索引”
- python-3.x - 如何将 4d numpy 数组转换为 PIL 图像?
- php - file_get_contents 没有获得所有内容