我正在尝试将 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/