2015-09-05 72 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` 
}