【发布时间】:2018-08-21 11:24:54
【问题描述】:
我无法将具有泛型类型的结构放入一个数组中。我知道 Swift 将 Array 的元类型转换为具体类型,这就是冲突。我试图找到一个不同的解决方案,但我想我需要你的帮助。
这里我定义了结构和协议:
protocol ItemProtocol {
var id: String { get }
}
struct Section<T: ItemProtocol> {
var items: [T]
var renderer: Renderer<T>
}
struct Renderer<T> {
var title: (T) -> String
}
这里有两个实现ItemProtocol的示例结构:
struct Book: ItemProtocol {
var id: String
var title: String
}
struct Car: ItemProtocol {
var id: String
var brand: String
}
这就是我设置这些部分的方式:
let book1 = Book(id: "1", title: "Foo")
let book2 = Book(id: "2", title: "Bar")
let books = [book1, book2]
let bookSection = Section<Book>(items: books, renderer: Renderer<Book> { (book) -> String in
return "Book title: \(book.title)"
})
let car1 = Car(id: "1", brand: "Foo")
let car2 = Car(id: "2", brand: "Bar")
let cars = [car1, car2]
let carSection = Section<Car>(items: cars, renderer: Renderer<Car> { (car) -> String in
return "Car brand: \(car.brand)"
})
现在我想把这些部分放在一起。这是我尝试过的。但是这 3 行中的每一行都给我一个错误:
let sections: [Section<ItemProtocol>] = [bookSection, carSection]
let sections2: [Section] = [bookSection, carSection]
let sections3: [Section<AnyObject: ItemProtocol>] = [bookSection, carSection]
sections.forEach({ section in
section.items.forEach({ item in
let renderedTitle = section.renderer.title(item)
print("\(renderedTitle)")
})
})
对于 sections 数组的声明,我收到此错误:
不支持将“ItemProtocol”用作符合协议“ItemProtocol”的具体类型
对于sections2数组的声明这个错误:
无法将“Section”类型的值转换为预期的元素类型“Section”
sections3 抛出这个:
预期 '>' 完成通用参数列表
【问题讨论】: