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

时间:2015-01-01 04:50:51

标签: ios iphone xcode swift dictionary

错误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

    }
})
}

编辑:

第二期:

    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'

        }
    })
    }

1 个答案:

答案 0 :(得分:14)

如果您打算返回一个词典,那么您需要指定其中的键和数据类型。

例如:如果您的密钥和值都是字符串,那么您可以编写如下内容:

class func getCurrentWeather(longitude: Float, latitude: Float) -> Dictionary <String, String>?
{
   ...
}

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

class func getCurrentWeather(longitude: Float, latitude: Float) -> NSDictionary?
{
    ...
}

您可以这样写:

class func getCurrentWeather(longitude: Float, latitude: Float) -> Dictionary <String, AnyObject>?
{
   ...
}