Home > Blockchain >  Is is complusory to use "in" keyword in closure? If no then what is the difference between
Is is complusory to use "in" keyword in closure? If no then what is the difference between

Time:03-26

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

CodePudding user response:

greet is a closure. A computed property is

var greet : Int {
  return 4 3
}

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)

CodePudding user response:

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
  • Related