"array" is not available: build an array from your lazy sequence: Array (...) error

Just upgraded to swift 2.0 and I have a bug.

The error I get is: "array" is not available: build an array from your lazy sequence: Array (...)

My code is:

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!)") } } } 

Does anyone know how to convert this line of code to upgrade for Swift 2.0?

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

+5
source share
2 answers

As the error says, you have to build an Array . Try:

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

In Swift1.2, values on Dictionary<Key, Value> returns LazyForwardCollection<MapCollectionView<[Key : Value], Value>> type that has a .array property that returns Array<Value> .

In Swift2, values on Dictionary<Key, Value> returns LazyMapCollection<[Key : Value], Value> , and the .array property .array abandoned because we can build an Array using Array(dict.values) .

In this case, since credentialStorage?.credentialsForProtectionSpace(protectionSpace)?.values ends with the Optional type, we cannot just Array(credentialStorage?.cre...) . Instead, if you want Array , we should use map() on Optional .

But in this particular case, you can use credentialStorage?.credentialsForProtectionSpace(protectionSpace)?.values as it is.

Try:

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

This works because the LazyMapCollection matches the SequenceType .

+9
source

Use initializer in Swift 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` } 
0
source

All Articles