[英]Protocol conformance is not inferred for an Element of the Collection
我有一组协议能够在UITableView中显示元素:
protocol TableRepresentableRow {
var title: String { get }
var subtitle: String { get }
}
extension TableRepresentableRow {
var title: String {return ""}
var subtitle: String {return ""}
}
protocol TableRepresentableSection {
var title: String { get }
var count: Int { get }
subscript(index: Int) -> TableRepresentableRow {get}
}
extension TableRepresentableSection {
var title: String {
return ""
}
}
单个元素符合TableRepresentableRow协议:
extension ServicesSummary.Service: TableRepresentableRow {
var title: String {
return serviceNumber
}
var subtitle: String {
return serviceUserName
}
}
我希望协议一致性也可以在TableRepresentableSection中进行推断,因为ServicesSummary.Service是TableRepresentableRow,但是,这不会发生:
extension Array: TableRepresentableSection where Element == ServicesSummary.Service {
// Error: the compiler requires me to add subscript too, while it should be inferred
subscript(index: Int) -> TableRepresentableRow {
<#code#>
}
var title: String {
return first?.businessType.rawValue.uppercased() ?? ""
}
}
为什么会出现此错误?
要解决此问题,请将“元素类型”检查更改为“仅协议”:
更改:
where Element == ServicesSummary.Service
至:
where Element == TableRepresentableRow
整个扩展名:
extension Array: TableRepresentableSection where Element == TableRepresentableRow {
var title: String {
return first?.businessType.rawValue.uppercased() ?? ""
}
}
Array
扩展仅包含Array
下标函数,该函数返回Element
类型的对象-在这种情况下为ServicesSummary.Service
。 因此,编译器要求您实现的下标函数是TableRepresentableSection
协议中的下标函数,因为该函数具有不同的返回类型: TableRepresentableRow
。 您有2个选择:
Element
类型更改为TableRepresentableRow
TableRepresentableSection
删除下标功能 我完成了以下代码,从协议中完全删除了subscript
:
protocol TableRepresentableRow {
var title: String { get }
var subtitle: String { get }
}
extension TableRepresentableRow {
var title: String {return ""}
var subtitle: String {return ""}
}
protocol TableRepresentableSection {
var title: String { get }
var items: [TableRepresentableRow] { get }
}
extension TableRepresentableSection {
var title: String {
return ""
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.