'array'不可用:请从你的懒惰序列构造一个数组:Array(...)错误

时间:2015-09-05 01:40:20

标签: arrays swift alamofire swifty-json

刚刚更新到swift 2.0,我遇到了错误。

我得到的错误是:'array'不可用:请从您的懒惰序列构造一个数组:Array(...)

我的代码是:

            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

2 个答案:

答案 0 :(得分:9)

如错误所述,您应构建Array。尝试:

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

在Swift1.2中,values上的Dictionary<Key, Value>会返回LazyForwardCollection<MapCollectionView<[Key : Value], Value>>类型,其.array属性返回Array<Value>

在Swift2中,values上的Dictionary<Key, Value>会返回LazyMapCollection<[Key : Value], Value>,而.array属性会被放弃,因为我们可以使用Array构建Array(dict.values)

在这种情况下,由于credentialStorage?.credentialsForProtectionSpace(protectionSpace)?.valuesOptional类型结尾,我们不能简单地Array(credentialStorage?.cre...)。相反,如果您想要Array,我们应该在map()上使用Optional

但是,在这种特殊情况下,您可以按原样使用credentialStorage?.credentialsForProtectionSpace(protectionSpace)?.values

尝试:

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

这可行,因为LazyMapCollection符合SequenceType

答案 1 :(得分:0)

在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`
}