在通用swift函数中键入cast

时间:2016-03-20 12:09:48

标签: swift generics

假设我有一个具有相同属性的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

}

这是避免大量代码重复的好方法吗?

2 个答案:

答案 0 :(得分:2)

鉴于您的模型类型

struct Event {
    let title: String
    let desc: String
}

定义此协议

protocol EventCell: class {
    var id: String? { get set }
    var desc: String? { get set }
}

现在使您的UITabelViewCellUICollectionViewCell符合

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
    }
}

那就是它。现在,您的单元格(UITabelViewCellUICollectionViewCell)都采用populate方法!

答案 1 :(得分:2)

这与您的想法相符吗?

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)