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

标签 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)
    }
}

可以看到,里面有一个数组。我正在通过函数 addItemtoElements 添加一些其他结构,如 element_flight 到这个数组中。

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

然后我尝试使用 TableView 创建列表:

    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
}

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

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

最佳答案

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

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

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

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

如果您只是要在元素中存储一些类型,而不是Any类型,创建一个协议(protocol)并使所有您要存储的类型符合它。至少你得到了一点类型安全。

假设您的数组只包含两个结构: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
}

关于ios - Swift 中一个数组中的不同结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38416819/

相关文章:

ios - 使用 NSPredicate 在一次搜索 iOS swift 中搜索多个单词

ios - React Native 从相机胶卷中获取照片名称 [ios]

ios - 在 UICollectionViewReusableView header 中访问 UIViews 的委托(delegate)方法

ios - 切换方向时从堆栈 View 中删除的元素

c++ - 使用 OpenCV 在 C++ 中缩放图像,但不使用 pyrDown() 或 pyrUp() 函数

java - 两个do while循环

ios - 三个按钮同时添加/删除GradientLayer

ios - 如何删除出现在 uitableview 下方的空白

ios - 为 Transformable 属性更改 Transformer 时是否需要进行核心数据迁移?

ios - ionic 1 ios 发布构建失败 Visual studio 2015