Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Blocks or closures in Swift

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 279
    Comment on it

    Hi Readers,

    We used to code blocks in Objective C, mainly to implement callbacks. For that particular functionality we can use closures in Swift. That will work same as blocks in Objective C. Closures are enclosed in curly braces { } and are defined by a function type () -> (), where arrow separates the arguments and the return type, followed by the in keyword which defines its body. Standard definition of closure is :
     

    { (params) -> returnType in
    
      //statements
    
    } 

    For example declaration of closure can be done as:

    var categoryNameClosure: ((categoryName: String) -> ())
    

    And definition where we need to get categoryName with callback can be written as:

    categoryNameClosure = {(categoryName: String) -> () in
                
                print(skillName)
                
    }

    In the declaration we set argument as catogoryName which is type of string without any return type. So you can easily modify according to requirement and define closure for callbacks in Swift.

     

    Happy Coding.

 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: