刚更新到 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 中,values
在 Dictionary<Key, Value>
返回 LazyForwardCollection<MapCollectionView<[Key : Value], Value>>
具有 .array
的类型属性(property)归还Array<Value>
.
在 Swift2 中,values
在 Dictionary<Key, Value>
返回 LazyMapCollection<[Key : Value], Value>
, 和 .array
属性(property)被放弃,因为我们可以 build Array
与 Array(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/