输入'String!'不符合协议'Equatable'

时间:2014-09-25 08:20:51

标签: ios swift

如何在swift iOS 8.0中解决此问题,即Type 'String!' does not conform to protocol 'Equatable'

这是我的代码

func connection(connection: NSURLConnection, canAuthenticateAgainstProtectionSpace protectionSpace: NSURLProtectionSpace?) -> Bool
{
    return protectionSpace?.authenticationMethod == NSURLAuthenticationMethodServerTrust
// Here I got this error near == sign
}

func connection(connection: NSURLConnection, didReceiveAuthenticationChallenge challenge: NSURLAuthenticationChallenge?)
{
    if challenge?.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust
    {
        if challenge?.protectionSpace.host == "www.myhost.com"

// Here I got this error near == sign

        {
            let credentials = NSURLCredential(forTrust: challenge!.protectionSpace.serverTrust)
            challenge!.sender.useCredential(credentials, forAuthenticationChallenge: challenge)
        }
    }

    challenge?.sender.continueWithoutCredentialForAuthenticationChallenge(challenge)
}

1 个答案:

答案 0 :(得分:0)

我不同意有关简单升级到最新版本的解决方案的评论。在进行其他比较之前It's a better practice to unwrap optionals with a nil check。我会重写你的代码(虽然比需要的更冗长),如下所示,这也应该在所有版本中修复你的问题:

func connection(connection: NSURLConnection, canAuthenticateAgainstProtectionSpace protectionSpace: NSURLProtectionSpace?) -> Bool
{
    if let authenticationMethod = protectionSpace?.authenticationMethod 
    {
        return authenticationMethod == NSURLAuthenticationMethodServerTrust
    }

    return false
}

func connection(connection: NSURLConnection, didReceiveAuthenticationChallenge challenge: NSURLAuthenticationChallenge?)
{
    if let authenticationMethod = challenge?.protectionSpace.authenticationMethod
    {
        if authenticationMethod == NSURLAuthenticationMethodServerTrust
        {
            if challenge?.protectionSpace.host == "www.myhost.com"
            {
                let credentials = NSURLCredential(forTrust: challenge!.protectionSpace.serverTrust)
                challenge!.sender.useCredential(credentials, forAuthenticationChallenge: challenge)
            }
        }
    }

    challenge?.sender.continueWithoutCredentialForAuthenticationChallenge(challenge)
}