[英]Type casting in a generic swift function
假設我有一個具有相同屬性的UICollectionViewCell和UITableViewCell。 除了可以使用兩個函數填充這些單元格之外,我還可以使用一個泛型來獲取某些東西,確定是什么,然后將其轉換為正確的東西,以在返回之前對其執行操作嗎?
我的想法是:
func setUpCell<T>(event: Event, cell:T) -> T {
// figure out what T is and cast it
cell.event.bar = event.bar
return cell
}
這是避免大量代碼重復的好方法嗎?
根據您的模型類型
struct Event {
let title: String
let desc: String
}
定義這個協議
protocol EventCell: class {
var id: String? { get set }
var desc: String? { get set }
}
現在使您的UITabelViewCell
和UICollectionViewCell
符合它
class TableCell: UITableViewController, EventCell {
var id: String?
var desc: String?
}
class CollectionCell: UICollectionViewCell, EventCell {
var id: String?
var desc: String?
}
最后定義這個擴展
extension EventCell {
func populate(event:Event) {
self.id = event.id
self.desc = event.desc
}
}
而已。 現在,您的兩個單元格( UITabelViewCell
和UICollectionViewCell
)都具有populate
方法!
這符合您的想法嗎?
import UIKit
struct Event {
var bar:Int = 0
}
// Protocol to group common additions
protocol ViewCellAdditions {
init()
var separatorInset:Int { get set }
var event:Event { get set}
}
// Generic function to work on any class that adopts ViewCellAdditions
func setUpCell<T: ViewCellAdditions>(event: Event, cell:T, foo:Int) -> T {
var newCell = T()
newCell.separatorInset = foo
newCell.event.bar = event.bar
return newCell
}
// Class that adopts ViewCellAdditions
class NewCellClass: ViewCellAdditions {
required init() {}
var separatorInset:Int = 10
var event:Event = Event()
}
// How to use it
let aCell = NewCellClass()
let aEvent = Event()
let newCell = setUpCell(aEvent, cell: aCell, foo: 5)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.