Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to handle two different types in an Array in Swift for a UITableView

We are thinking of migrating an app from obj-c to Swift. One issue is that we have a UITableView in our obj-c code that has objects that are either of type Header or of type Item. Basically, it resolves which type it has at cellForRowAtIndexPath. Swift Arrays (to the best of my knowledge) can only handle a single type. Given this, how could we handle two different types to be used in a UITableView? Would a wrapper object like DataObj where we have nillable instance of each work?

like image 932
timpone Avatar asked Jun 10 '15 15:06

timpone


2 Answers

Here is an approach that uses a protocol to unite your two classes:

protocol TableItem {

}

class Header: TableItem {
    // Header stuff
}

class Item: TableItem {
    // Item stuff
}

// Then your array can store objects that implement TableItem
let arr: [TableItem] = [Header(), Item()]

for item in arr {
    if item is Header {
        print("it is a Header")
    } else if item is Item {
        print("it is an Item")
    }
}

The advantage of this over [AnyObject] or NSMutableArray is that only the classes which implement TableItem would be allowed in your array, so you gain the extra type safety.

like image 139
vacawama Avatar answered Sep 30 '22 21:09

vacawama


Swift arrays can store objects of different types. To do so you must declare as AnyObject array

var array:[AnyObject] = []

After this on cellForRowAtIndexPath you can get type of object using optional unwrapping

if let header = array[indexPath.row] as? Header{
    //return header cell here
}else{

    let item = array[indexPath.row] as! Item

    // return item cell

}
like image 39
Zell B. Avatar answered Sep 30 '22 21:09

Zell B.