xcode Swift:一个数组中的不同对象?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27548239/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Swift: different objects in one array?
提问by fahu
Is there a possibility to have two different custom objects in one array?
是否有可能在一个数组中包含两个不同的自定义对象?
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.
我想在 a 中显示两个不同的对象UITableView
,我认为最简单的方法是将所有对象放在一个数组中。
回答by George M
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.
根据您想要对数组进行多少控制,您可以创建两个对象类型都实现的协议。该协议不需要包含任何内容(将是 Java 中的标记接口,不确定 Swift 中是否有特定名称)。这将允许您将数组限制为您想要的对象类型。请参阅下面的示例代码。
protocol MyType {
}
class A: MyType {
}
class B: MyType {
}
var array = [MyType]()
let a = A()
let b = B()
array.append(a)
array.append(b)
回答by redent84
You can use AnyObject
array to hold any kind of objects in the same array:
您可以使用AnyObject
数组在同一个数组中保存任何类型的对象:
var objectsArray = [AnyObject]()
objectsArray.append("Foo")
objectsArray.append(2)
// And also the inmutable version
let objectsArray: [AnyObject] = ["Foo", 2]
// This way you can let the compiler infer the type
let objectsArray = ["Foo", 2]
回答by Kolja
If you know the types of what you will store beforehand, you could wrap them in an enumeration. This gives you more control over the types than using [Any/AnyObject]
:
如果您事先知道要存储的内容的类型,则可以将它们包装在枚举中。与使用相比,这使您可以更好地控制类型[Any/AnyObject]
:
enum Container {
case IntegerValue(Int)
case StringValue(String)
}
var arr: [Container] = [
.IntegerValue(10),
.StringValue("Hello"),
.IntegerValue(42)
]
for item in arr {
switch item {
case .IntegerValue(let val):
println("Integer: \(val)")
case .StringValue(let val):
println("String: \(val)")
}
}
Prints:
印刷:
Integer: 10
String: Hello
Integer: 42
回答by return true
You can use the "type" AnyObject
which allows you to store objects of different type in an array. If you also want to use structs, use Any
:
您可以使用“类型” AnyObject
,它允许您在数组中存储不同类型的对象。如果您还想使用结构,请使用Any
:
let array: [Any] = [1, "Hi"]