如何在 Swift 中为 UITableView 处理数组中的两种不同类型 [英] how to handle two different types in an Array in Swift for a UITableView

查看:27
本文介绍了如何在 Swift 中为 UITableView 处理数组中的两种不同类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在考虑将应用程序从 obj-c 迁移到 Swift.一个问题是我们的 obj-c 代码中有一个 UITableView,它具有类型为 Header 或类型为 Item 的对象.基本上,它会解析它在 cellForRowAtIndexPath 中的类型.Swift 数组(据我所知)只能处理一种类型.鉴于此,我们如何处理要在 UITableView 中使用的两种不同类型?像 DataObj 这样的包装器对象,我们有每个工作的 nillable 实例吗?

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")
    }
}

相对于 [AnyObject]NSMutableArray 的优势在于,只有实现了 TableItem 的类才会被允许在你的数组中,所以您获得了额外的类型安全性.

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 中为 UITableView 处理数组中的两种不同类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆