简体   繁体   中英

Type casting in a generic swift function

Supposing I have a UICollectionViewCell and a UITableViewCell with identical properties. 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

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!

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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