Reputation: 19969
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?
Upvotes: 6
Views: 4896
Reputation: 154593
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.
Upvotes: 19
Reputation: 10286
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
}
Upvotes: 4