简体   繁体   中英

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?

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.

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

}

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