Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Basic Differences in Optional, Non Optional Value and How to Use Closures in Swift

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 1
    • 0
    • 706
    Comment on it

    In this tutorial, we are going to learn the difference between optional and non optional value in swift. We represent optional value by question mark i.e “?” and non optional value by exclamation mark i.e “!”.

     

    Non optional value also called unwrapping of value. 

    For example ->

    var possibleString: String? // optional string

    It means possibleString may be nil or may not be. In both the conditions app will not crash.

     

    But if we write like this ->

    var possibleString: String!  // non optional string

    it means possibleString should not be nil and must contain some value otherwise app will crash.

     

    Closures in swift

    If we have to pass the value back then we use Closures. As we know whenever we send value form one view controller to another we use segue but sending value back to previous view controller we use closures. Suppose on button click which is placed in table view cell we have to get the index so in cell class we will write below code.

    Syntax of Closures

      var closuresName: (() -> Void)?  // declaration of Closure
    
    
     @IBAction func someButtonClicked(sender: AnyObject) {
            // on button click we have to call the  Closure
    
            if self.closuresName != nil {
                self.closuresName!()
            }//block
            
        }

    Below code will be written in controller class

    cell.closuresName = {
                   
      classVariable = index // saving closure value to previous class variable
                           
         }

     

    Basic Differences in Optional, Non Optional Value and How to Use Closures in Swift

 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: