let loginRegisterButton:UIButton = {
let button = UIButton(type: .system)
button.backgroundColor = .white
button.setTitle("Register", for: .normal)
button.translatesAutoresizingMaskIntoConstraints = false
button.setTitleColor(.white, for: .normal)
return button
}()
is this variable or function , why does it return value? why do we call it? it does not work without parenthesis
,why?
Brackets, or braces, are a syntactic construct in many programming languages. They take the forms of "[]", "()", "{}" or "<>." They are typically used to denote programming language constructs such as blocks, function calls or array subscripts. Brackets are also known as braces.
{} (curly braces)Define the beginning and end of functions blocks and statement blocks such as the for and if structures. Curly braces are also used for defining initial values in array declarations.
Rules to Using Brackets, Braces, and ParenthesesUse Parentheses to insert or add comments to your writing. Use brackets for editorial purposes, to insert comments into someone else's work. Use brackets, braces, and parenthesis in pairs, one at the beginning of a sentence and the other at the end.
Curly braces { } are special syntax in JSX. It is used to evaluate a JavaScript expression during compilation. A JavaScript expression can be a variable, function, an object, or any code that resolves into a value.
This is a closure created and used in the same spot. You use it for initialization when you cannot put everything in a single expression. This feature is helpful when creating read-only (let
, as opposed to var
) fields.
In the case above, the code creates a button, and then performs additional configuration on it before returning the result. This is a good way to move code from init
into code blocks near the place of initialization.
One way to visualize what's going on is to think of a named function that does the same thing:
func makeWhiteButton() -> UIButton {
let button = UIButton(type: .system)
button.backgroundColor = UIColor.White
button.setTitle("Register", for: .normal)
button.translatesAutoresizingMaskIntoConstraints = false
button.setTitleColor(.white, for: .normal)
return button
}
Now you can use it in an initializer
let loginRegisterButton:UIButton = makeWhiteButton()
The code from your post does the same thing with an anonymous "closure" function. The parentheses after the closure block are there for the same reason as the parentheses after makeWhiteButton
above.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With