skip to Main Content

In swift use of get and set is not compulsory and if use of "in" in closure is also not compulsory then how to differentiate a closure and computed property?

Like in below example greet is a closure or computed property?

var greet = {
  return 4+3
}

greet()

2

Answers


  1. greet is a closure. A computed property is

    var greet : Int {
      return 4+3
    }
    
    greet // without parentheses
    

    And "in" in closure is also not compulsory if a parameter is passed (by the way the return keyword is not compulsory)

    var greet = { x in
      4+x
    }
    
    greet(4)
    

    unless you use the shorthand syntax

    var greet = {
       4+$0
    }
    
    greet(4)
    
    Login or Signup to reply.
  2. You use the keyword in when you need to pass a parameter.

    There are also differences between functions and computed properties: if you use the symbol =, you are equalling your variable to a function, so you need to call greet().

    If instead = you use :, you have a computed property, call greet.

    Here’s a list of different cases:

            // greet is a function, you need to call greet()
            var greet = {
              return 4 + 3
            }
            print(greet()) // 7
    
            // greet2 is a computed property, you need to call greet2
            var greet2: Int {
                return 4 + 3
            }
            print(greet2) // 7
    
            // greet3 is a function that receives one parameter, you need to call greet3(someInt)
            var greet3 = { (parameter: Int) -> Int in
              return 4 + parameter
            }
            print(greet3(4)) // 8
    
            // greet4 is like greet3, but the type is declared outside
            var greet4: (Int)->Int = { parameter in
                return 4 + parameter
            }
            print(greet4(5)) // 9
    
            // greet5 is like greet4, where you define the function later
            var greet5: (Int) -> Int
            greet5 = { parameter in
                return 4 + parameter
            }
            print(greet5(6)) // 10
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search