arrays - “数组”不可用 : please construct an Array from your lazy sequence: Array(. ..) 错误

标签 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

最佳答案

如错误所述,您应该构造 Array .尝试:

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

在 Swift1.2 中,valuesDictionary<Key, Value>返回 LazyForwardCollection<MapCollectionView<[Key : Value], Value>>具有 .array 的类型属性(property)归还Array<Value> .

在 Swift2 中,valuesDictionary<Key, Value>返回 LazyMapCollection<[Key : Value], Value> , 和 .array属性(property)被放弃,因为我们可以 build ArrayArray(dict.values) .

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

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

尝试:

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

这是有效的,因为 LazyMapCollection符合 SequenceType .

关于arrays - “数组”不可用 : please construct an Array from your lazy sequence: Array(. ..) 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32408722/

相关文章:

ios - 在 UIWebView 中渲染二进制 ms/doc 为空

ios - Alamofire 响应与请求不匹配

ios - Xcode 7 无法加载 AlamoFire 3.x (CocoaPods) 的底层模块

arrays - 在 MATLAB 中替换矩阵值

Java-如何将黑白图像加载到二进制中?

javascript - 循环数组仅捕获第一个元素后,在一个文本字段上在线获取多个数据 仅 JavaScript

ios - JSON 数组 Swift 的索引

C编程 "weird output"

ios - AnyObject 到阵列?

ios - 在 Storyboard 中,UIViewController 的宽度不是 iPhone 的宽度