user6587892
user6587892

Reputation:

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

            }
        })

    }

Upvotes: 3

Views: 88

Answers (2)

Dave Weston
Dave Weston

Reputation: 6635

It sounds like you might be converting if statements into guard let statements, which require an Optional type.

You should be able to use just a straight guard something like:

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

NOTE: This doesn't actually compile because the code is trying to redefine the success and errormsg constants, but it should give you the general idea.

Upvotes: 0

Tj3n
Tj3n

Reputation: 9923

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 {...}

Upvotes: 2

Related Questions