假设您有以下结构和协议:
struct Ticket {
var items: [TicketItem] = []
}
struct TicketItem {
}
protocol DisplayableTicket {
var displayedItems: [DisplayableTicketItem] { get }
}
protocol DisplayableTicketItem {}
现在,如果我要扩展这些结构:
extension Ticket: DisplayableTicket {
var displayedItems: [DisplayableTicketItem] {
return self.items
}
}
extension TicketItem: DisplayableTicketItem {}
我在第return self.items
行上收到以下错误:
Cannot convert return expression of type '[TicketItem]' to return type 'DisplayableTicketItem'
如果我将Ticket和TicketItem的类型更改为class
,我不会收到错误。为什么Ticket结构不能包含TicketItem结构数组并如上所述进行扩展?
答案 0 :(得分:1)
像这样:
extension Ticket: DisplayableTicket {
var displayedItems: [DisplayableTicketItem] {
return self.items.map{$0 as DisplayableTicketItem}
}
}