Burak Pusat Burak Pusat - 2 months ago 78
Swift Question

Type "Any" has no subscript members / Swift 3

Everything was working fine in Swift 2but after Swift 3 upgrade it is failing. It is simply giving the following error: "Type "Any" has no subscript members" on the following line:

for video in JSON["items"] as? NSArray {

My previous question and solution to it can be found here:
Ambiguous use of 'subscript' with NSArray & JSON

I have also looked through the suggested questions and answers while typing my question but couldn't come up with a solution so far.

class videoModel: NSObject {

let API_KEY = "Xxxxxxxxxxx"

let UPLOADS_PLAYLIST_ID = "yyyyyyyyyyyyyyy"


var videoArray = [Video]()

var delegate: VideoModelDelegate?

let urladdress = "https://www.googleapis.com/youtube/v3/playlistItems"


func getFeedVideos() {

Alamofire.request((urladdress), method: .get, parameters: ["part":"snippet", "playlistId": UPLOADS_PLAYLIST_ID,"key": API_KEY, "maxResults": "50"], encoding: JSONEncoding.default).responseJSON(completionHandler: { (response) -> Void in

if let JSON = response.result.value {

var arrayOfVideos = [Video]()

print(JSON)

for video in JSON["items"] as? NSArray {

let videoObj = Video()
videoObj.videoId = video.valueForKeyPath("snippet.resourceId.videoId") as! String
videoObj.videoTitle = video.valueForKeyPath("snippet.title") as! String
videoObj.videoDescription = video.valueForKeyPath("snippet.description") as! String
videoObj.videoThumbnailUrl = video.valueForKeyPath("snippet.thumbnails.maxres.url") as! String

arrayOfVideos.append(videoObj)

}

self.videoArray = arrayOfVideos

if self.delegate != nil {

self.delegate?.dataReady()

}
}
})
}
}

Answer

You need to specify the type of your JSON object to [String : Any].

 if let JSON = response.result.value  as?  [String : Any] {
       if let items =  JSON["items"] as? [[String : Any]] {
            for video in items {
                  //Here use video["snippet.resourceId.videoId"] instead of value for key
            }
       }
 }

Note : In swift it is batter if you use swift generic Array and dictionary objects instead of NSArray & NSDictionary.