Closure used when creating the UI
Closures are particularly common in SwiftUI, so I’ve redefined closures here.
About the closure
The general form of closure expression syntax is as follows:
{(parameters) -> return type in
/ / code
}
Copy the code
Closure expressions are written in curly braces ({}), and the keyword in is used to separate the closure arguments, return values, and statements inside the closure
// Pass the closure a sort method
arr.sort(by: { (a: Int, b: Int) - >Bool in
return a > b
})
// Closures can take advantage of Swift's type inference capabilities and omit the return type, as well as the type of the parameter
arr.sort(by: { a, b in
return a > b
})
// remove the keyword return. Not all closure statements can remove the return keyword
// This can be because there is only one expression (I < j). If there are more expressions, then an explicit return is required.
arr.sort(by: { a, b in a > b })
// Swift provides shortcut parameter names that can be used in inline closure expressions
arr.sort(by: { $0 > $1})
// If a closure is passed as the last argument to a function, it can be inlined outside the function's parentheses.
arr.sort{$0 > $1 }
Copy the code
Closure assignment variable
// Common mode
var str: String = "str"
// The closure runs assignment
var str2: String = {
return "str2"} ()// Simplify based on the closure principle
var str3: String = {
"str3"} ()// If you do not need to pass arguments, the "=" sign before the closure and the "()" at the end can also be omitted
var str4: String {
"str4"
}
Copy the code
Closure in SwiftUI
Use closures extensively in declarative UI creation, such as
import SwiftUI
struct Text: View {
var body: some View {
Button(action: {
print("Button Click") {})Text("Hello World!")}}}Copy the code
Here we use closures to create a View, a Button, and a Button
public struct Button<Label> : View where Label : View {
/// Creates an instance for triggering `action`.
///
/// - Parameters:
/// - action: The action to perform when `self` is triggered.
/// - label: A view that describes the effect of calling `action`.
public init(action: @escaping () -> VoidThe @ViewBuilder label: () -> Label)
/// Declares the content and behavior of this view.
public var body: some View { get }
/// The type of view representing the body of this view.
///
/// When you create a custom view, Swift infers this type from your
/// implementation of the required `body` property.
public typealias Body = some View
}
Copy the code
The init method sets two arguments, both of function type, that can be used using Swift’s tail-closure syntax: if a closure is passed as the last argument to a function, it can be inlined outside the function’s parentheses, so Button can be written like this
Button(action: {
print("Button Click") {})Text("Hello World!")}Copy the code
Or you could write it this way
Button(action: { print("Button Click") }, label: { Text("Hello World!")})Copy the code