首页 > 解决方案 > 泛型函数参数的多重约束

问题描述

阅读 Swift 中的泛型函数,我发现可以通过要求对参数施加一些约束,要求它是给定类 C 的子类,或者它实现给定协议 P。但我想知道是否存在同时要求两者的方法。我还没有找到任何关于它的东西。

有人知道吗?

标签: swiftgeneric-programming

解决方案


其实你可以这样做。

如果你在 swift 中看到它 Codable实际上是DecodableEncodable

 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用作通用约束的 任何方法


推荐阅读