Swift错误:引用通用类型字典需要< ...>中的参数 [英] Swift error: Reference to generic type Dictionary requires arguments in <...>
问题描述
错误引用通用类型字典需要< ...>
中的参数出现在函数的第一行。我试图让函数返回从api检索的NSDictionary。任何人都知道这里可能发生什么?
The error Reference to generic type Dictionary requires arguments in <...>
is appearing on the first line of the function. I am trying to have the function return an NSDictionary retrieved from an api. Anyone know what could be going on here?
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
}
})
}
编辑:
第二个问题:
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'
}
})
}
推荐答案
如果您打算返回一个Dictionary,那么您需要指定其中的键和数据类型。
If you are planning to return a Dictionary then you need to specify the type of key and data in it.
例如:如果您的键和值都是字符串,那么您可以编写以下内容: / p>
Eg: If your key and value both are Strings then you can write something like:
class func getCurrentWeather(longitude: Float, latitude: Float) -> Dictionary <String, String>?
{
...
}
如果不是确保其中的数据,或者如果您有多种类型的数据,请将返回类型从字典
更改为 NSDictionary
。
If you are not sure about the data in it or if you have multiple type of data, change the return type from Dictionary
to NSDictionary
.
class func getCurrentWeather(longitude: Float, latitude: Float) -> NSDictionary?
{
...
}
或
你可以写如下:
class func getCurrentWeather(longitude: Float, latitude: Float) -> Dictionary <String, AnyObject>?
{
...
}
这篇关于Swift错误:引用通用类型字典需要< ...>中的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!