2015-09-05 71 views
5

剛剛更新到swift 2.0,並且出現錯誤。'array'is unavailable:Please construct an Array from your lazy sequence:Array(...)error

我得到的錯誤是:'數組' 不可用:請從你的懶惰序列構建一個數組:數組(...)

我的代碼是:

  if let credentialStorage = session.configuration.URLCredentialStorage { 
      let protectionSpace = NSURLProtectionSpace(
       host: URL!.host!, 
       port: URL!.port?.integerValue ?? 0, 
       `protocol`: URL!.scheme, 
       realm: URL!.host!, 
       authenticationMethod: NSURLAuthenticationMethodHTTPBasic 
      ) 
// ERROR------------------------------------------------↓ 
      if let credentials = credentialStorage.credentialsForProtectionSpace(protectionSpace)?.values.array { 
// ERROR------------------------------------------------↑ 
       for credential: NSURLCredential in (credentials) { 
        components.append("-u \(credential.user!):\(credential.password!)") 
       } 
      } else { 
       if let credential = delegate.credential { 
        components.append("-u \(credential.user!):\(credential.password!)") 
       } 
      } 
     } 

會任何人都知道如何將這行代碼轉換爲Swift 2.0更新?

if let credentials = credentialStorage.credentialsForProtectionSpace(protectionSpace)?.values.array

+0

什麼版本的Xcode的? – pixyzehn

+0

它在我的操場上工作。 – pixyzehn

+0

@pixyzehn這是版本7測試版6個 – Bills

回答

9

由於錯誤狀態,你應該建立Array。嘗試:

if let credentials = (credentialStorage?.credentialsForProtectionSpace(protectionSpace)?.values).map(Array.init) { 
    //... 
} 

在Swift1.2,valuesDictionary<Key, Value>返回具有.array的財產返還Array<Value>LazyForwardCollection<MapCollectionView<[Key : Value], Value>>類型。

在Swift2,valuesDictionary<Key, Value>回報LazyMapCollection<[Key : Value], Value>.array財產被放棄,因爲我們可以構造ArrayArray(dict.values)

在這種情況下,由於credentialStorage?.credentialsForProtectionSpace(protectionSpace)?.values結尾爲Optional類型,我們不能簡單Array(credentialStorage?.cre...)。相反,如果您需要Array,我們應該在Optional上使用map()

但是,在這種特殊情況下,你可以使用credentialStorage?.credentialsForProtectionSpace(protectionSpace)?.values原樣。

嘗試:

if let credentials = credentialStorage?.credentialsForProtectionSpace(protectionSpace)?.values { 
    for credential in credentials { 
     //... 
    } 
} 

這工作,因爲LazyMapCollection符合SequenceType

+1

'(dict.keys).MAP(Array.init)'我沒有工作(我結束了與'元素'推理錯誤)但[MyType](dict.keys)'工作(在這裏找到:http://stackoverflow.com/a/32243072/63582) – wmmeyer

0

使用初始化的雨燕2.0

guard let values = credentialStorage?.credentialsForProtectionSpace(protectionSpace)?.values else { return } 
let credentials = Array<NSURLCredential>(values) 
for credential in credentials { 
    // `credential` will be a non-optional of type `NSURLCredential` 
}