'Is it complusory to use "in" keyword in closure? If no then what is the syntax wise difference between closure and computed property in swift?
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()
Solution 1:[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)
Solution 2:[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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | HunterLion |