ClaytonAV
ClaytonAV

Reputation: 95

Swift - Parse Multiple Optionals Json Answer

The code bellow is working fine, at least in my few tests. The problem is that i really don't know if i cover every possible fail in the code or if this is the best way to handle with multiples "if let..." Optionals . Is there a better and more practical way to do this ? The code is just to process the data that i am getting from the Youtube API.

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()
            }
        }
    }

Since the answer can for example don´t have a "thumbnail" or "title", i already got some answers like that, i have to check for everything or the app will crash.

Just to let you know, this is one item in the answer

{
    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";
    };
}

Thanks in advance.

Upvotes: 0

Views: 70

Answers (1)

Michael
Michael

Reputation: 9044

You can chain the "if let" code together so at least it doesn't look so ugly. Then instead of having;

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

You just have

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

Then you only need to deal with one else condition.

Upvotes: 1

Related Questions