gpt4 book ai didi

arrays - FOR IN 循环出错

转载 作者:行者123 更新时间:2023-11-30 13:42:44 24 4
gpt4 key购买 nike

我正在尝试在 for in 循环中为数组 quandlURLs 运行以下函数。我在“loadDataFromURL”行中收到错误,提示:无法将 [String] 类型的值转换为“Sting”类型的预期参数。有人可以告诉我我在这里缺少什么吗?谢谢!!

class func getDataFromQuandlWithSuccess(success: ((Quandl: NSData!) -> Void)) {
let quandlGold = "https://www.quandl.com/api/v3/datasets/LBMA/GOLD.json?auth_token=xyzDP7Cj-2F_Jss7sYHf&rows=1"
quandlURLs = [quandlGold, quandlSilver,quandlPlatinum,quandlPalladium]
var index: Int
var urlData = [String]()
for index in quandlURLs {
loadDataFromURL(NSURL(string: quandlURLs[index])!, completion:{(data, error) -> Void in
//2
if let urlData[index] = data {
//3
success(Quandl: urlData[index])
//below worked and showed raw data
//print("Successful \(urlData)")

}
})

}
}

这是 loadDataFromURL 函数

class func loadDataFromURL(url: NSURL, completion:(data: NSData?, error: NSError?) -> Void) {
let session = NSURLSession.sharedSession()

// Use NSURLSession to get data from an NSURL
let loadDataTask = session.dataTaskWithURL(url, completionHandler: { (data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
if let responseError = error {
completion(data: nil, error: responseError)
} else if let httpResponse = response as? NSHTTPURLResponse {
if httpResponse.statusCode != 200 {
let statusError = NSError(domain:"com.raywenderlich", code:httpResponse.statusCode, userInfo:[NSLocalizedDescriptionKey : "HTTP status code has unexpected value."])
completion(data: nil, error: statusError)
} else {
completion(data: data, error: nil)
}
}
})

loadDataTask.resume()
}
}

最佳答案

您需要在这里做的就是更改 for index in quandlURLsfor index in 0..<quandlURLs.count

if let urlData[index] = data 也存在问题,因为不能对数组使用可选绑定(bind),所以需要定义一个新值,所以转到 if let urlDataEntry = data ,在这种情况下,您的 urlIndex 数组应该是 NSData 类型。

您也不需要 var index: Int线。在创建 Int 数组的 ..< 函数上使用 for in 循环时,会推断出 Int,并且索引变量在整个 for 循环中都可用。

例如:

class func getDataFromQuandlWithSuccess(success: ((Quandl: NSData!) -> Void)) {
let quandlGold = "https://www.quandl.com/api/v3/datasets/LBMA/GOLD.json?auth_token=xyzDP7Cj-2F_Jss7sYHf&rows=1"
quandlURLs = [quandlGold, quandlSilver,quandlPlatinum,quandlPalladium]
var urlData = [NSData]()
for index in 0..<quandlURLs.count {
loadDataFromURL(NSURL(string: quandlURLs[index])!, completion:{(data, error) -> Void in
//2
if let urlDataEntry = data {
//3
urlData[index] = urlDataEntry
success(Quandl: urlDataEntry)
//below worked and showed raw data
//print("Successful \(urlData)")

}
})

}
}

关于arrays - FOR IN 循环出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35377315/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com