s_k*_*les 10 iphone xcode dictionary ios swift
错误Reference to generic type Dictionary requires arguments in <...>
出现在函数的第一行.我试图让函数返回从api检索到的NSDictionary.有谁知道这里会发生什么?
class func getCurrentWeather(longitude: Float, latitude: Float)->Dictionary?{
let baseURL = NSURL(string: "https://api.forecast.io/forecast/\(apikey)/")
let forecastURL = NSURL(string: "\(longitude),\(latitude)", relativeToURL:baseURL)
let sharedSession = NSURLSession.sharedSession()
let downloadTask: NSURLSessionDownloadTask = sharedSession.downloadTaskWithURL(forecastURL!, completionHandler: { (location: NSURL!, response: NSURLResponse!, error: NSError!) -> Void in
if(error == nil) {
println(location)
let dataObject = NSData(contentsOfURL:location!)
let weatherDictionary: NSDictionary = NSJSONSerialization.JSONObjectWithData(dataObject!, options: nil, error: nil) as NSDictionary
return weatherDictionary
}else{
println("error!")
return nil
}
})
}
Run Code Online (Sandbox Code Playgroud)
编辑:
第二期:
class func getCurrentWeather(longitude: Float, latitude: Float)->NSDictionary?{
let baseURL = NSURL(string: "https://api.forecast.io/forecast/\(apikey)/")
let forecastURL = NSURL(string: "\(longitude),\(latitude)", relativeToURL:baseURL)
let sharedSession = NSURLSession.sharedSession()
let downloadTask: NSURLSessionDownloadTask = sharedSession.downloadTaskWithURL(forecastURL!, completionHandler: { (location: NSURL!, response: NSURLResponse!, error: NSError!) -> Void in
if(error == nil) {
println(location)
let dataObject = NSData(contentsOfURL:location!)
let weatherDictionary: NSDictionary = NSJSONSerialization.JSONObjectWithData(dataObject!, options: nil, error: nil) as NSDictionary
return weatherDictionary //ERROR: NSDictionary not convertible to void
}else{
println("error!")
return nil ERROR: Type void does not conform to protocol 'NilLiteralConvertible'
}
})
}
Run Code Online (Sandbox Code Playgroud)
Mid*_* MP 14
如果您计划返回字典,则需要指定其中的键和数据类型.
例如:如果您的键和值都是字符串,那么您可以编写如下内容:
class func getCurrentWeather(longitude: Float, latitude: Float) -> Dictionary <String, String>?
{
...
}
Run Code Online (Sandbox Code Playgroud)
如果您不确定其中的数据或者您有多种类型的数据,请将返回类型更改Dictionary
为NSDictionary
.
class func getCurrentWeather(longitude: Float, latitude: Float) -> NSDictionary?
{
...
}
Run Code Online (Sandbox Code Playgroud)
要么
你可以这样写:
class func getCurrentWeather(longitude: Float, latitude: Float) -> Dictionary <String, AnyObject>?
{
...
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
15623 次 |
最近记录: |