2016-02-11 2 views
0

Код ниже работает, по крайней мере, в моих тестах. Проблема в том, что я действительно не знаю, покрываю ли я все возможные сбои в коде или если это лучший способ обработки с помощью мультиплексов «if let ...» Optionals. Есть ли лучший и более практичный способ сделать это? Код - это просто обработка данных, которые я получаю от Youtube API.Swift - Parse Multiple Optionals Json Answer

func requestPlaylistTrailers(){ 
     let playlist = self.playlistIdTrailers 
     self.delegate?.youtubeTrailersWillUpdate() 
     self.req(playlist) { (myData) -> Void in 
      var title = "" 
      var videoId = "" 
      var thumbnail = "" 
      if myData != nil{ 
       let data = myData! 
       let items = data["items"] as! Array<AnyObject> 
       for item in items { 
        //print(item) 
        if let itemDict = item as? Dictionary<NSObject,AnyObject>{ 
         if let snippet = itemDict["snippet"] as? Dictionary<NSObject,AnyObject> { 
          if let getTitle = snippet["title"] as? String{ title = getTitle} 
          if let getVideoId = snippet["resourceId"] as? Dictionary<NSObject,AnyObject> { 
           if let getVideoId2 = getVideoId["videoId"] as? String{ videoId = getVideoId2} 
          } 
          if let myThumb = snippet["thumbnails"] as? Dictionary<NSObject,AnyObject>{ 
           if let myHighThumb = myThumb["high"] as? Dictionary<NSObject,AnyObject>{ 
            if let thumbUrl = myHighThumb["url"] as? String{ 
             thumbnail = thumbUrl 
            } 
           } 
          } 
         } 
        } 
        if (thumbnail != "" && videoId != ""){ 
         self.arrayYoutubeTrailers.append(["title": title,"videoId": videoId, "thumbnail": thumbnail]) 
        } 
       } 
       self.delegate?.youtubeTrailersDidUpdate(self.arrayYoutubeTrailers) 
      } else { 
       self.delegate?.youtubeTrailersFailed() 
      } 
     } 
    } 

Поскольку ответ может, например, уже не надо в «миниатюру» или «название», я уже получил ответы на некоторые вопросы, как, что, я должен проверить все или приложение будет врезаться.

Просто, чтобы вы знаете, это один пункт в ответ

{ 
    contentDetails =  { 
     videoId = "va-0o_xBVnU"; 
    }; 
    etag = "\"DsOZ7qVJA4mxdTxZeNzis6uE6ck/spb02vX6UoYkYSIcBFTCzlPQ3Es\""; 
    id = "PLegkaUUrMBQZ7KYS4cdBhF5aRmyOFe-zLBqlqoAM_wH4"; 
    kind = "youtube#playlistItem"; 
    snippet =  { 
     channelId = UCi8e0iOVk1fEOogdfu4YgfA; 
     channelTitle = "Movieclips Trailers"; 
     description = "Subscribe to TRAILERS: http://bit.ly/sxaw6h\nSubscribe to COMING SOON: http://bit.ly/H2vZUn\nLike us on FACEBOOK: http://goo.gl/dHs73\nFollow us on TWITTER: http://bit.ly/1ghOWmt \nMoney Monster Official Trailer #1 (2016) - George Clooney, Julia Roberts Movie HD\n\nIn the taut and tense thriller Money Monster, Lee Gates (George Clooney) is a bombastic TV personality whose popular financial network show has made him the money wiz of Wall Street. But after he hawks a high tech stock that mysteriously crashes, an irate investor (Jack O'Connell) takes Gates, his crew, and his ace producer Patty Fenn (Julia Roberts) hostage live on air. Unfolding in real time, Gates and Fenn must find a way to keep themselves alive while simultaneously uncovering the truth behind a tangle of big money lies.\n\n\nThe Fandango MOVIECLIPS Trailers channel is your destination for the hottest new trailers the second they drop. Whether it's the latest studio release, an indie horror flick, an evocative documentary, or that new RomCom you've been waiting for, the Fandango MOVIECLIPS team is here day and night to make sure all the best new movie trailers are here for you the moment they're released.\n\nIn addition to being the #1 Movie Trailers Channel on YouTube, we deliver amazing and engaging original videos each week. Watch our exclusive Ultimate Trailers, Showdowns, Instant Trailer Reviews, Monthly MashUps, Movie News, and so much more to keep you in the know.\n\nHere at Fandango MOVIECLIPS, we love movies as much as you!"; 
     playlistId = "PLScC8g4bqD47c-qHlsfhGH3j6Bg7jzFy-"; 
     position = 26; 
     publishedAt = "2016-01-13T17:25:53.000Z"; 
     resourceId =   { 
      kind = "youtube#video"; 
      videoId = "va-0o_xBVnU"; 
     }; 
     thumbnails =   { 
      default =    { 
       height = 90; 
       url = "https://i.ytimg.com/vi/va-0o_xBVnU/default.jpg"; 
       width = 120; 
      }; 
      high =    { 
       height = 360; 
       url = "https://i.ytimg.com/vi/va-0o_xBVnU/hqdefault.jpg"; 
       width = 480; 
      }; 
      maxres =    { 
       height = 720; 
       url = "https://i.ytimg.com/vi/va-0o_xBVnU/maxresdefault.jpg"; 
       width = 1280; 
      }; 
      medium =    { 
       height = 180; 
       url = "https://i.ytimg.com/vi/va-0o_xBVnU/mqdefault.jpg"; 
       width = 320; 
      }; 
      standard =    { 
       height = 480; 
       url = "https://i.ytimg.com/vi/va-0o_xBVnU/sddefault.jpg"; 
       width = 640; 
      }; 
     }; 
     title = "Money Monster Official Trailer #1 (2016) - George Clooney, Julia Roberts Movie HD"; 
    }; 
} 

Спасибо заранее.

+0

Ответы Майклса вместе с SwiftyJSON будут творить чудеса. –

ответ

1

Вы можете связать код «if let» вместе, по крайней мере, он не выглядит таким уродливым. Тогда вместо наличия;

if let ... 
    if let ... 
     if let ... etc 

Вы просто

if let ..., 
    let ..., 
    let ... { 
    // All good, do stuff 
} else { 
    // Something went wrong 
} 

Тогда вам нужно иметь дело только с одним другим состоянием.

+0

Спасибо @ Майкл, это, безусловно, поможет. – ClaytonAV