fahu
fahu

Reputation: 1531

Swift: different objects in one array?

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.

Upvotes: 7

Views: 11386

Answers (4)

George M
George M

Reputation: 186

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)

Upvotes: 12

Kolja
Kolja

Reputation: 1247

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]:

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

Upvotes: 8

return true
return true

Reputation: 7916

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:

let array: [Any] = [1, "Hi"]

Upvotes: 2

redent84
redent84

Reputation: 19239

You can use AnyObject array to hold any kind of objects in the same array:

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]

Upvotes: 6

Related Questions