0

I just updated to Xcode7 and am trying to switch my project to using the Swift 2.0 Syntax when I ran into this error in a file from an open source library I'm using. Here's the relevant code:

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
    }()

The error reads: Cannot assign a value of type '[NSHTTPCookie]' to a value of type '[NSHTTPCookie]'

Is there something I'm missing here?

zrzka
  • 20,249
  • 5
  • 47
  • 73
Pat
  • 3
  • 2

1 Answers1

2

Change your code to this:

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
  }()

Changes:

  • if let responseHeaders ... line - did add as? [String:String], because allHeadersFields return type is [NSObject : AnyObject] and not [String:String] required by cookiesWithResponseHeaderFields...

  • removed as! [NSHTTPCookie] - it has no sense, because cookiesWithResponseHeaderFields return type is already [NSHTTPCookie]

Just check cookiesWithResponseHeaderFields signature:

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

Please read How do I ask a good question. At least, you should point out to lines where the problem is, etc.

Community
  • 1
  • 1
zrzka
  • 20,249
  • 5
  • 47
  • 73
  • This worked, thanks! Apologies for not pointing out the specific line, and thanks for the reference. – Pat Jul 13 '15 at 16:16
  • You're welcome. Remember - more info about your problem provided (even if you think it's not important), quicker working answer without additional questions. – zrzka Jul 13 '15 at 16:31