Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to Use Guard Statement in Swift iOS Application

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 1
    • 0
    • 50
    Comment on it

    Guard statement work as an error handler. If we have to send values to server which can be empty or may not be in that condition we can use guard so that if the value is nil then app will not get crashed.

     

     

    let's see how to use Guard Statement in Swift.

    example:

    
    func submittingToServer() {
    
        guard let name = nameField.text else {
            show("No name to submit") // if not unwrapped this line will display
            return
        }
    
        guard let address = addressField.text else {
            show("No address to submit")
            return
        }
    
        guard let phone = phoneField.text else {
            show("No phone to submit")
            return
        }
    
        valuesSendToServer(name, address: address, phone: phone)
    }
    
    func valuesSendToServer(name: String, address: String, phone: String) {
      ...// sending non optional values
    }

    As we can see we are sending non optional strings to the server so server may or may not get nil values, to avoid this situation we use guard. It will unwrap the values and if unwrapping fails you will get some text which is written in else statement.

    How to Use Guard Statement in Swift iOS Application

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: