xcode 7无法将类型'[NSHTTPCookie]'的值赋给类型'[NSHTTPCookie]'的值

时间:2015-07-13 14:00:52

标签: xcode swift swift2

我刚刚更新到Xcode7,并且我试图将我的项目切换到使用Swift 2.0语法,当我在一个来自我正在使用的开源库的文件中遇到此错误时。这是相关的代码:

public lazy var cookies:[String:NSHTTPCookie] = {
    let foundCookies: [NSHTTPCookie]
    if let responseHeaders = (self.response as? NSHTTPURLResponse)?.allHeaderFields {
        foundCookies = NSHTTPCookie.cookiesWithResponseHeaderFields(responseHeaders, forURL:NSURL(string:"")!) as! [NSHTTPCookie]
    } else {
        foundCookies = []
    }
    var result:[String:NSHTTPCookie] = [:]
    for cookie in foundCookies {
        result[cookie.name] = cookie
    }
    return result
    }()

错误显示:无法将类型'[NSHTTPCookie]'的值分配给类型'[NSHTTPCookie]'的值

这里有什么我想念的吗?

1 个答案:

答案 0 :(得分:2)

将您的代码更改为:

public lazy var cookies:[String:NSHTTPCookie] = {
  let foundCookies: [NSHTTPCookie]
  if let responseHeaders = (self.response as? NSHTTPURLResponse)?.allHeaderFields as? [String:String] {
    foundCookies = NSHTTPCookie.cookiesWithResponseHeaderFields(responseHeaders, forURL:NSURL(string:"")!)
  } else {
    foundCookies = []
  }
  var result:[String:NSHTTPCookie] = [:]
  for cookie in foundCookies {
    result[cookie.name] = cookie
  }
  return result
  }()

的变化:

  • if let responseHeaders ...行 - 确实添加了as? [String:String],因为allHeadersFields要求[NSObject : AnyObject]返回类型[String:String而不是cookiesWithResponseHeaderFields...}

  • 已删除as! [NSHTTPCookie] - 这没有任何意义,因为cookiesWithResponseHeaderFields返回类型已经[NSHTTPCookie]

只需检查cookiesWithResponseHeaderFields签名:

class func cookiesWithResponseHeaderFields(headerFields: [String : String],
  forURL URL: NSURL) -> [NSHTTPCookie]

请阅读How do I ask a good question。至少,你应该指出问题所在的行等等。