泛型函数参数的多重约束
Multiple constraints on parameter of a generic function
阅读 Swift 中的通用函数,我发现可以通过要求对参数施加一些约束,它是给定 class 的子class 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) {
}
另一种方法是协议,class 都可以有超级 class。所以你可以创建通用协议
喜欢
protocol CommonInProtocolAndStruct { }
protocol ProtocolUsedAsConstraint:CommonInProtocolAndStruct {}
struct StructUsedAsConstraint:CommonInProtocolAndStruct {}
您可以使用任何方法 CommonInProtocolAndStruct
作为通用约束
您可以使用 where
子句添加任意数量的类型约束。示例:
import UIKit
func f<T>(t: T) where T: UIView, T: Encodable {}
class C<T> where T: UIView, T: Encodable {}
阅读 Swift 中的通用函数,我发现可以通过要求对参数施加一些约束,它是给定 class 的子class 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) {
}
另一种方法是协议,class 都可以有超级 class。所以你可以创建通用协议
喜欢
protocol CommonInProtocolAndStruct { }
protocol ProtocolUsedAsConstraint:CommonInProtocolAndStruct {}
struct StructUsedAsConstraint:CommonInProtocolAndStruct {}
您可以使用任何方法 CommonInProtocolAndStruct
作为通用约束
您可以使用 where
子句添加任意数量的类型约束。示例:
import UIKit
func f<T>(t: T) where T: UIView, T: Encodable {}
class C<T> where T: UIView, T: Encodable {}