Swift:一个数组中的不同对象? [英] Swift: different objects in one array?

查看:108
本文介绍了Swift:一个数组中的不同对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能在一个数组中有两个不同的自定义对象?

Is there a possibility to have two different custom objects in one array?

我想在 UITableView中显示两个不同的对象我认为最简单的方法是将所有对象放在一个数组中。

I want to show two different objects in a UITableView and I think the easiest way of doing this is to have all objects in one array.

推荐答案

取决于您希望对阵列进行多少控制,您可以创建两种对象类型实现的协议。该协议不需要包含任何内容(在Java中是标记接口,不确定Swift中是否有特定名称)。这将允许您将数组限制为只有您想要的对象类型。请参阅下面的示例代码。

Depending on how much control you want over the array, you can create a protocol that both object types implement. The protocol doesn't need to have anything in it (would be a marker interface in Java, not sure if there is a specific name in Swift). This would allow you to limit the array to only the object types you desire. See the sample code below.

protocol MyType {

}


class A: MyType {

}

class B: MyType {

}

var array = [MyType]()

let a = A()
let b = B()

array.append(a)
array.append(b)

这篇关于Swift:一个数组中的不同对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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