Swift中一个数组中的不同结构

时间:2016-07-17 00:21:57

标签: ios arrays swift xcode struct

我有一个名为trip的结构。

struct trip {
    var name: String
    var description: String
    var elements: [Any] = []

    mutating func addItemToElements(newValue: Any) {
       elements.append(newValue)
    }
}

如您所见,内部有一个数组。我通过函数element_flightaddItemtoElements等其他结构添加到此数组中。

struct element_flight {
    var origin: String
    var destination: String
    var flightno: String
    var departure: NSDate
    var arrival: NSDate
    var seat: String
}

然后我尝试使用表格视图创建列表:

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "elementTrip", for: indexPath) as! CellInElementsOfTripsTableViewCell
    let elem = trips[0].elements[indexPath.row]
    cell.mainTextLabel.text = elem.origin //it doesn't work

    return cell
}

我无法获得struct的任何部分(例如代码中的origin)。我做错了什么?

我正在为element_flight创建类似的结构,这可能是将它放在一个数组中然后在表格视图中显示的最佳方式。

2 个答案:

答案 0 :(得分:3)

一个简单,天真的解决方案是将elem转换为正确的类型:

cell.mainTextLabel.text = (elem as! element_flight).origin

但是,由于elements数组可以存储Any,如果elem是其他类型,该怎么办?显然,它会崩溃!

我不明白你为什么要在Any中存储一堆elements。这是一个标志或坏代码。 Swift中很少使用Any

如果您要在Any中存储某些类型而非elements类型,请创建协议并制作要存储的所有类型符合它。至少你得到了一点安全性。

假设您的数组只包含两个结构:element_flightSomeOtherStruct。你应该这样做:

protocol SomeProtocol { // please give this a proper name yourself
    // properties/methods that are common among element_flight and SomOtherStruct
}

struct element_flight: SomeProtocol {
    // ...
}

struct SomeOtherStruct: SomeProtocol {
    // ...
}

将数组更改为[SomeProtocol]类型。

现在在cellForRowAtIndexPath方法中,您需要测试elemelement_flight还是SomeOtherStruct

if let flight = elem as? element_flight {
    cell.mainTextLabel.text = flight.origin
} else if let someOtherStuff = elem as? SomeOtherStruct {
    // do some other stuff
} else {
    // something's wrong if this is executed, maybe call fatalError
}

答案 1 :(得分:0)

你应该将它们转换为element_flight(使用此名称而不是override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "elementTrip", for: indexPath) as! CellInElementsOfTripsTableViewCell if let flightInfo = trips[0].elements[indexPath.row] as? FlightInfo { cell.mainTextLabel.text = flightInfo.origin //it doesn't work } return cell } - Swift中的类型名称应该用CamelCase编写。)

{
  "restriction-type": "boolean-search-restriction",
  "boolean-logic": "and",
  "restrictions": [
    {
      "restriction-type": "property-search-restriction",
      "property": {
        "name": "name",
        "type": "STRING"
      },
      "match-mode": "EXACTLY_MATCHES",
      "value": "admin"
    },
    {
      "restriction-type": "property-search-restriction",
      "property": {
        "name": "email",
        "type": "STRING"
      },
      "match-mode": "EXACTLY_MATCHES",
      "value": "admin@example.com"
    }
  ]
}