类型“Any”没有下标成员/ Swift 3

时间:2016-09-28 17:35:01

标签: ios swift alamofire

在Swift 3升级后Swift 2but中的一切都运行良好,但它失败了。它只是给出以下错误:

  

类型“任何”没有下标成员

在以下一行:

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

            }
        }
    })
}
}

我之前的问题和解决方案可以在这里找到:

Ambiguous use of 'subscript' with NSArray & JSON

我在输入问题时也查看了建议的问题和答案,但到目前为止还没有找到解决方案。

ionic plugin rm ionic-plugin-keyboard    
ionic plugin add ionic-plugin-keyboard

1 个答案:

答案 0 :(得分:1)

您需要将JSON对象的类型指定为[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
            }
       }
 }

注意:在swift中,如果使用swift通用数组和字典对象而不是NSArray& NSDictionary