Swift: different objects in one array?

后端 未结 4 1115
鱼传尺愫
鱼传尺愫 2021-02-06 14:06

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

4条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-06 14:52

    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
    

提交回复
热议问题