简体   繁体   English

如何在Swift中为UITableView处理数组中的两种不同类型

[英]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. 我们正在考虑将应用程序从obj-c迁移到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 . 一个问题是我们的obj-c代码中有一个UITableView,它具有Header类型或Item类型的对象。 Basically, it resolves which type it has at cellForRowAtIndexPath. 基本上,它解析了它在cellForRowAtIndexPath中的类型。 Swift Arrays (to the best of my knowledge) can only handle a single type. Swift Arrays(据我所知)只能处理一种类型。 Given this, how could we handle two different types to be used in a UITableView? 鉴于此,我们如何处理UITableView中使用的两种不同类型? Would a wrapper object like DataObj where we have nillable instance of each work? 像DataObj这样的包装器对象我们每个工作都有可用的实例吗?

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. 这个优于[AnyObject]NSMutableArray的优点是只允许在您的数组中实现TableItem的类,因此您可以获得额外的类型安全性。

Swift arrays can store objects of different types. Swift数组可以存储不同类型的对象。 To do so you must declare as AnyObject array 为此,您必须声明为AnyObject数组

var array:[AnyObject] = []

After this on cellForRowAtIndexPath you can get type of object using optional unwrapping cellForRowAtIndexPath之后,您可以使用可选的展开来获取对象类型

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

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

    // return item cell

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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