简体   繁体   English

在通用Swift函数中进行类型转换

[英]Type casting in a generic swift function

Supposing I have a UICollectionViewCell and a UITableViewCell with identical properties. 假设我有一个具有相同属性的UICollectionViewCell和UITableViewCell。 Rather than have two functions which populate those cells, could I have a generic that takes something , determine what that was and then cast it to the correct thing to perform actions on it before returning? 除了可以使用两个函数填充这些单元格之外,我还可以使用一个泛型来获取某些东西,确定是什么,然后将其转换为正确的东西,以在返回之前对其执行操作吗?

my thinking is: 我的想法是:

func setUpCell<T>(event: Event, cell:T) -> T {

    // figure out what T is and cast it
    cell.event.bar = event.bar
    return cell

}

is this a good way of avoiding large amounts of code duplication? 这是避免大量代码重复的好方法吗?

Given your model type 根据您的模型类型

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

define this protocol 定义这个协议

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

Now conform your UITabelViewCell and UICollectionViewCell to it 现在使您的UITabelViewCellUICollectionViewCell符合它

class TableCell: UITableViewController, EventCell {
    var id: String?
    var desc: String?
}

class CollectionCell: UICollectionViewCell, EventCell {
    var id: String?
    var desc: String?
}

And finally define this extension 最后定义这个扩展

extension EventCell {
    func populate(event:Event) {
        self.id = event.id
        self.desc = event.desc
    }
}

That's it. 而已。 Now both your cells ( UITabelViewCell and UICollectionViewCell ) have the populate method! 现在,您的两个单元格( UITabelViewCellUICollectionViewCell )都具有populate方法!

Does this match what you were thinking? 这符合您的想法吗?

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM