【发布时间】:2021-12-22 15:30:53
【问题描述】:
我有以下方法:
private func returnNilIfEmpty<T: Collection>(_ collection: T?) -> T? {
guard let collection = collection else { return nil }
return collection.isEmpty ? nil : collection
}
我想扩展Collection API 以使用计算变量来提取非空值,如下所示:
extension Collection {
var nonEmptyValue: Collection? {
returnNilIfEmpty(self)
}
}
但是,我收到了错误:
Protocol 'Collection' 只能用作通用约束,因为 它有 Self 或关联的类型要求
这很清楚,因为外部 Collection 可以是任何集合(例如 [Int]),而 returnNilIfEmpty 内部的集合可以是例如String。
问题是如何强制执行Collection通过nonEmptyValue返回的规则和通过returnNilIfEmpty返回的相同类型的规则,以便我可以摆脱这个编译器错误?
【问题讨论】:
标签: ios arrays swift generics swift-protocols