在一个泛型函数的参数多约束

问题描述 投票:0回答:2

阅读关于雨燕的通用功能,我看到它有可能把一些约束上的一个参数,要求,这是一个给定的C类的子类,或者说,它实现了一个给定的协议P.但我不知道是否有一个在同一时间的方式既需要。我还没有发现关于任何东西。

有人知道吗?

swift generic-programming
2个回答
3
投票

其实你可以做到这一点。

如果你已经看到了迅速Codable它实际上是DecodableEncodable

 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作为通用的限制


1
投票

您可以添加任意数量的使用where条款类型约束。例子:

import UIKit

func f<T>(t: T) where T: UIView, T: Encodable {}

class C<T> where T: UIView, T: Encodable {}
© www.soinside.com 2019 - 2024. All rights reserved.