Search code examples
iosswiftguard

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


I want to change the following if statements to guards. Doing so throws the following error Initializer for conditional binding must have Optional type, not '(Bool, String)' Any idea how I should go about it? Any help will be appreciated. Thank you

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)
                }

            }
        })

    }

Solution

  • Because you declare the variable without the ? (non optional) and also given it default value so the guard assume it never nil thats why u got the error, u still can use guard like this guard let object: Type = data else {...}