我怎样才能解开阵列?

时间:2016-11-03 22:06:04

标签: arrays uitableview swift3

打开数组时遇到问题。我不确定我是否正确地做了,请帮助:

这是我的字典:

class NewsModel: NSObject {
    var data :NSArray = []
    var title :String = ""
    var urlImage: String = ""
    var link: String = ""
}

这里是Json Parse:

 let json = try JSONSerialization.jsonObject(with: result as! Data, options: .mutableContainers) as? NSDictionary
                if let parseJSON = json{
                    let newsModel = NewsModel()
                    let status = parseJSON["status"] as! Bool
                    if (status) {
                        let data = parseJSON["data"] as! NSArray
                        newsModel.data = data
                        storeProtocols[Actions.getNews]?.onSuccess(type, result: newsModel)
                    } else {
                        let error = parseJSON["error"] as! NSDictionary
                        storeProtocols[Actions.getNews]?.onError(type, error: error)
                    }
                }

最后,我试图在UITableView中显示我的数组:

var newsModel = NewsModel()

 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let notifications = self.newsModel.data.count
        return notifications
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell()
        let notifications = self.newsModel.data[indexPath.row]
        cell.textLabel!.text = String(describing: (notifications as! NSDictionary).value(forKey: "title"))
        return cell   
    }

但我的问题是我获得了" Optional"数组值之前的图例,如下所示:

TableView Result

1 个答案:

答案 0 :(得分:1)

您获得可选 String的原因是(notifications as! NSDictionary).value(forKey: "title")

extension NSDictionary {
    /* Return the result of sending -objectForKey: to the receiver.
    */
    open func value(forKey key: String) -> Any?
}

返回可选 Any,对于您的特定情况,它将是可选 String

所以你需要打开可选 String以获得String,有很多方法可以打开,但最安全的方法是可选解包。

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  let cell = UITableViewCell()
  let notifications = self.newsModel.data[indexPath.row]

  if let dictionary = notifications as? NSDictionary {
    if let title = dictionary.value(forKey: "title") as? String {
      cell.textLabel?.text = title
    }
  }

  return cell
}

如果你有时间,可以阅读一些关于 Optionals 的内容,我已经创建了一篇关于它的帖子:https://medium.com/@wilson.balderrama/what-are-optionals-in-swift-3-b669ca4c2f12#.rb76h4r9k