ios - 当调用 Swift 2 时不断返回一个空数组

标签 ios arrays swift swift2

我正在尝试将 vidar 附加到 videoArray 中,它可以工作,但只能在 Alamofire block 中使用。当我尝试将计数移出它的一侧时,我得到返回 0,但在 Alamofire 一侧阻止我返回 5。我猜这与范围有关?我正在调用函数 getFeedVideos()在我的里面viewDidLoad

let APIKey = "AIzaSyBF1fGTvY4Z73jNBRFlxiSDelt4zqMnNCg"
var videoArray = [VideoObj]()

// main function
func getFeedVideos (){

    // Fetch video data
    Alamofire.request(.GET, "https://www.googleapis.com/youtube/v3/playlistItems", parameters: ["part":"snippet", "playlistId": "PL8kma_GjQgWzBLAciqmwC4duAPcSRyt8T", "key":APIKey], encoding: ParameterEncoding.URL, headers: nil).responseJSON { (response) -> Void in

        var vidar = [VideoObj]()

        if let value = response.result.value {
            var arrayofvideos = [VideoObj]()

            // loop
            for videos in value["items"] as! NSArray {

                let videoObject = VideoObj()

                videoObject.videoID = videos.valueForKeyPath("snippet.resourceId.videoId") as! String
                videoObject.videoTitle = videos.valueForKeyPath("snippet.title") as! String
                videoObject.videoDescription = videos.valueForKeyPath("snippet.description") as! String
                videoObject.vidoeoThumbUrl = videos.valueForKeyPath("snippet.thumbnails.maxres.url") as! String

                arrayofvideos.append(videoObject)

            } // For loop ends

            //print(arrayofvideos.count) // Prints out 5, which is correct
            //print(arrayofvideos[0].videoTitle) // Prints out video title


            //  P A R S E  print("JSON: \(value)")

            //

            vidar = arrayofvideos


        }  // If Statement ends


        print(vidar.count) // prints 5
        self.videoArray = vidar
        print(self.videoArray) // prints array

    } // AlamoFire Ends


    // ** Anything in there returns 0 ** //



    print("\(videoArray.count)  count ") // But this array prints out 0 !?!?
    //print(arrayofvideos[0].videoTitle) // No title "fatal error: Array index out of range"


} // Function End

最佳答案

是的,这与变量videoArray的范围有关。 videoArray 的作用域是 getFeedsVideos() 函数的本地范围。 vidar 也是如此。要增加这些变量的范围,您可以通过在类的顶部声明它们来将它们移动到实例级别。

关于ios - 当调用 Swift 2 时不断返回一个空数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35007850/

相关文章:

ios - 有没有办法在我的应用程序启动时获取最后的推送通知?

ios - 如何使用 Swift 上传 Evernote ENML 笔记?

jQuery 循环遍历 HTML5 数据属性

IOS COCOAPOD 及源码

ios - 如何以编程方式设置 TableView(而不是节)的变量 header ?

ios - 在我的 iOS 应用程序中创建模型类的正确要求是什么?

ios - 如何自动给图片添加二维码

ios - UIImageView+AFNetworking.h 文件未找到

javascript - 用新号码替换重复项

javascript - 想要从javascript文件调用php文件