Swift错误:对泛型类型Dictionary的引用需要<...>中的参数

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)

如果您不确定其中的数据或者您有多种类型的数据,请将返回类型更改DictionaryNSDictionary.

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)

  • "如果您不确定数据......将返回类型从`Dictionary`更改为`NSDictionary`" - 这不是一个好建议.如果您不确定类型,您应该弄明白,不要使用不关心的类型.这将导致后来更加混乱.如果你真的需要异构存储,你仍然应该使用带有"Any"或"AnyObject"的Dictionary.当你真正需要一个`NSDictionary`时,你应该只使用`NSDictionary`. (2认同)