阅读关于雨燕的通用功能,我看到它有可能把一些约束上的一个参数,要求,这是一个给定的C类的子类,或者说,它实现了一个给定的协议P.但我不知道是否有一个在同一时间的方式既需要。我还没有发现关于任何东西。
有人知道吗?
其实你可以做到这一点。
如果你已经看到了迅速Codable
它实际上是Decodable
和Encodable
typealias Codable = Decodable & Encodable
因此,在一些功能,如果你正在使用通用的T作为可编码
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
作为通用的限制
您可以添加任意数量的使用where
条款类型约束。例子:
import UIKit
func f<T>(t: T) where T: UIView, T: Encodable {}
class C<T> where T: UIView, T: Encodable {}