【问题标题】:Appending Model into array in Swift在 Swift 中将模型附加到数组中
【发布时间】:2017-06-14 06:01:14
【问题描述】:

所以我创建了一个模型类,我在其中使用 Alamofire 从 API 获取数据。我想在表格中显示该数据以查看,因此我正在考虑将该模型附加到 VC 中的数组中并在自定义单元格中调用它。

但我只想在键值与特定字符串匹配时将该模型附加到数组中。

但是,当我在 VC 中使用一个简单的 if 语句时,它给了我一个致命的错误,说错误的指令。

代码

调用模型

var notificationModel: NotificationModel!
var notification = [NotificationModel]()

viewDidLoad

if notificationModel.type == "meeting" {
    self.notification.append(notificationModel)
}

型号

Class NotificationModel

    var _type: String!

    var type: String {
        if _type == nil {
            _type = "Err"
        }
        return _type
    }

    func downloadData() {
          ... 
    }  
}

【问题讨论】:

  • 分享你的代码
  • 请分享您的代码。
  • 你是如何为 notificationModel 赋值的?
  • “notificationModel.type”的数据类型是什么?
  • @AmanChawla 你还没有初始化notificationModel,你需要在访问它的属性之前对其进行初始化。

标签: ios model-view-controller swift3 alamofire


【解决方案1】:

在这里您可以强制解开 NotificationModel。您正在尝试访问 nil 值的类型。 请尝试以下修复。

var notificationModel: NotificationModel! var notification = [NotificationModel]()

    if notificationModel?.type == "meeting" {
notification.append(notificationModel!)

}

希望这能解决问题。

【讨论】:

  • 数据没有显示,因为它没有执行 if 语句,因为 notificationModel 为 nil。所以 notificationModel?.type 也是 nil。
  • 我是 swift 新手,你能告诉我这应该如何正确完成吗?
  • 您可以对通知模型使用可选绑定,然后检查类型。请点击链接 Swift.org
猜你喜欢
  • 2015-08-30
  • 2015-06-14
  • 1970-01-01
  • 1970-01-01
  • 2018-10-15
  • 1970-01-01
  • 2020-01-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多