如何将此方法从Objective-C转换为Swift

时间:2015-02-23 15:13:05

标签: objective-c swift

我正在尝试将this class从Objective-C翻译为Swift。除了这个方法,我差不多完成了:

-(void) handleCookiesInRequest:(NSMutableURLRequest*) request
    {
    NSURL* url = request.URL;
    NSArray* cookies = [self cookiesForURL:url];
    NSDictionary* headers = [NSHTTPCookie requestHeaderFieldsWithCookies:cookies];

    NSUInteger count = [headers count];
    __unsafe_unretained id keys[count], values[count];
    [headers getObjects:values andKeys:keys];

    for (NSUInteger i=0;i<count;i++) {
        [request setValue:values[i] forHTTPHeaderField:keys[i]];
    }
}

我的尝试:

func handleCookiesInRequest(request: NSMutableURLRequest) {
    var url = request.URL
    var cookies = self.cookiesForURL(url!)
    var headers = NSHTTPCookie.requestHeaderFieldsWithCookies(cookies)

    var count = headers.count
    for i in 0...count {
        request.setValue(value: headers.values[i], forHTTPHeaderField: headers.keys[i])
    }
}

我在设置值

的行中收到错误
CustomHTTPCookieStorage.swift:88:21: Type '(value: $T8, forHTTPHeaderField: $T21)' does not conform to protocol '_SignedIntegerType'

你能帮助我吗?

1 个答案:

答案 0 :(得分:3)

NSHTTPCookie.requestHeaderFieldsWithCookies()返回字典,而不是数组。你的意思是:

for (key, value) in headers {
    request.setValue(value as? String, forHTTPHeaderField: key as! String)
}

你可以通过这种方式使这更安全:

if let headers = NSHTTPCookie.requestHeaderFieldsWithCookies(cookies) as? [String:String] {
    for (key, value) in headers {
        request.setValue(value, forHTTPHeaderField: key)
    }
}

当然,如果您尚未设置任何标题,则可以全部替换为:

request.allHTTPHeaderFields = NSHTTPCookie.requestHeaderFieldsWithCookies(cookies)

但这会吹走任何预设的标题,所以语义有点不同。