Swift: different objects in one array?

Is it possible to have two different user objects in the same array?

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

+4
source share
4 answers

Depending on what kind of control over the array is required, you can create a protocol that is implemented by both types of objects. The protocol should not have anything in it (it will be the token interface in Java, not sure if there is a specific name in Swift). This will allow you to restrict the array to only the desired types of objects. 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)
+7
source

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]
+4

If you know the types of what you will store in advance, you can wrap them in an enumeration. This gives you more control over types than with [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)")
  }
}

Print

Integer: 10
String: Hello
Integer: 42
+4
source

You can use a “type” AnyObjectthat allows you to store objects of another type in an array. If you also want to use structures, use Any:

let array: [Any] = [1, "Hi"]
+2
source

Source: https://habr.com/ru/post/1568160/


All Articles