2015-02-23 60 views
2

我正在嘗試將this class從Objective-C轉換爲Swift。我除了這個方法幾乎做到了:如何將此方法從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' 

你能幫我設定值行的錯誤?

+0

'value'的值是多少? – Fogmeister 2015-02-23 15:15:41

+0

對不起。我做了一個錯誤的方法。我剛剛更新了它。你能重新檢查嗎? – 2015-02-23 15:26:13

+0

這是我不明白的部分:__unsafe_unretained id鍵[count],values [count]; – 2015-02-23 15:26:45

回答

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) 

但是,這將吹走任何預設的標題,所以語義有點不同。

+0

太棒了!謝謝!我的問題和解釋發表評論也很有用。 – 2015-02-23 15:31:44

相關問題