Swift: different objects in one array?

后端 未结 4 1131
鱼传尺愫
鱼传尺愫 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条回答
  •  旧时难觅i
    2021-02-06 14:47

    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)
    

提交回复
热议问题