2016-11-03 9 views
0

配列をアンラップするときに問題が発生します。私はそれを正しくやっている場合、私はわからないんだけど、助けてください:JSON解析どのようにしてアレイをアンラップできますか?

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

ここ:

は、これは私の辞書で最後に私がしようとしている

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 
    } 

しかし、私の問題は、私はARRの値の前に「オプション」の伝説を得てるということですAY、次のように:

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

それはオプションなりますオプションAnyを返します:

TableView Result

+0

また、キー '「タイトル」の値は'すでにあります文字列。これを 'String(describe:)'に渡す理由はありません。 'cell.textLabel!.text'に直接割り当てるだけです。 – Alexander

+0

これはちょっと混乱していますが、データがどのようなものであるかに関する詳細情報を提供すれば、それをきれいにすることができます。 – Alexander

+0

これはNewsModelのデータです:{ "status":true、 "data":[ { "タイトル": "ヌエボEVENTOパラロスMASpequeños"、 "urlImage": "https://s-media-cache-ak0.pinimg.com/564x/48/bd/3f/48bd3f6e928d7cb4b8d499cb0f96b8a8.jpg"、 "リンク": "http:// ...." } ] } –

答えて

1

あなたはオプションStringを得ている理由は、(notifications as! NSDictionary).value(forKey: "title")があることですあなたの特別な場合はStringです。


だからStringを取得するためにオプションStringのラップを解除する必要があり、そこにアンラップする多くの方法がありますが、最も安全な1はオプションアンラップです。あなたは時間があるときに

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

関連する問題