将 if 语句更改为 guard 会引发此错误。条件绑定的初始化程序必须具有可选类型,而不是“(Bool, String)”

Changing an if statement to guard throws this error. Initializer for conditional binding must have Optional type, not '(Bool, String)'

我想将以下 if 语句更改为 guards。这样做会引发以下错误 条件绑定的初始化程序必须具有可选类型,而不是“(Bool, String)” 知道我应该怎么做吗? 任何帮助将不胜感激。谢谢

dispatch_async(backgroundQueue, {
            let (success, errmsg) = client.connect(timeout: 5)
            print("Connected",success)
            if success {
                let (success, errmsg) = client.send(str: self.jsonString)
                print("sent",success)

                if success {
                    let data = client.read(ApplicationConfig.expectedByteLength)
                    if let d = data {
                        if let recievedMsg = String(bytes: d, encoding: NSUTF8StringEncoding){
                            print(recievedMsg)
                            let (success, errormsg) = client.close()
                        }
                    }
                }else {
                    print("Message not sent", errmsg)
                }

            }
        })

    }

因为你声明的变量没有 ?(非可选)并且还给它默认值所以 guard 假设它永远不会 nil 这就是你得到错误的原因,你仍然可以像这样使用 guard guard let object: Type = data else {...}

听起来您可能正在将 if 语句转换为 guard let 语句,这需要可选类型。

你应该可以直接使用 guard 类似的东西:

    dispatch_async(backgroundQueue, {
        let (success, errmsg) = client.connect(timeout: 5)
        print("Connected",success)
        guard success else {
            return
        }

        let (success, errmsg) = client.send(str: self.jsonString)
        print("sent",success)

        guard success else {
            print("Message not sent", errmsg)
            return
        }

        let data = client.read(ApplicationConfig.expectedByteLength)
        guard let d = data else {
            return
        }
        guard let recievedMsg = String(bytes: d, encoding: NSUTF8StringEncoding) else {
            return
        }

        print(recievedMsg)
        let (success, errormsg) = client.close()
    })

注意:这实际上并没有编译,因为代码试图重新定义 success 和 errormsg 常量,但它应该为您提供总体思路。