swift - 泛型函数参数的多重约束
问题描述
阅读 Swift 中的泛型函数,我发现可以通过要求对参数施加一些约束,要求它是给定类 C 的子类,或者它实现给定协议 P。但我想知道是否存在同时要求两者的方法。我还没有找到任何关于它的东西。
有人知道吗?
解决方案
其实你可以这样做。
如果你在 swift 中看到它 Codable
实际上是Decodable
Encodable
typealias Codable = Decodable & Encodable
所以在某些功能中,如果您使用通用 T 作为 Codable
struct StructOfCodable<T:Codable>: Codable {
....
}
这是示例
protocol Test {}
class TClass {
}
typealias Common = Test & TClass
func generic <T:Common>(method:T) {
}
另一种方式是协议和类都可以有超类。所以你可以创建通用协议
喜欢
protocol CommonInProtocolAndStruct { }
protocol ProtocolUsedAsConstraint:CommonInProtocolAndStruct {}
struct StructUsedAsConstraint:CommonInProtocolAndStruct {}
以及可以 CommonInProtocolAndStruct
用作通用约束的 任何方法
推荐阅读
- reactjs - ReactJs redux 表单:传递给表单的初始值不显示
- java - 带有thymeleaf的Java spring-boot登录示例代码
- go - golang 模块和本地包
- javascript - SAPUi5 TypeError:I.fFunction.call 不是函数
- javascript - cytoscape.js 如何在 div 中显示节点?
- vb.net - 如何通过字符串从不同的项目/程序集中打开表单?
- javascript - 直到 N 个与 RXJS 相同的数字?
- php - 树枝宏可以返回值吗?
- java - 即使在设置 noCursorTimeout 后也找不到 mongo 光标
- node.js - 安装 nodejs 后 NVM for windows 错误