Multiple trailing closures
About 2 min
Multiple trailing closures 관련
HACKING WITH SWIFT
What's new in Swift?
Multiple trailing closures | Changes in Swift 5.3
Multiple trailing closures
Available from Swift 5.3
SE-0279 (apple/swift-evolution
) introduced multiple trailing closures, making for a simpler way to call a function with several closures.
This will be particularly welcome in SwiftUI, where code like this:
struct OldContentView: View {
@State private var showOptions = false
var body: some View {
Button(action: {
self.showOptions.toggle()
}) {
Image(systemName: "gear")
}
}
}
Can now be written as this:
struct NewContentView: View {
@State private var showOptions = false
var body: some View {
Button {
self.showOptions.toggle()
} label: {
Image(systemName: "gear")
}
}
}
Technically there is no reason why label:
needs to be on the same line as the preceding }
, so you could even write this if you wanted:
struct BadContentView: View {
@State private var showOptions = false
var body: some View {
Button {
self.showOptions.toggle()
}
label: {
Image(systemName: "gear")
}
}
}
However, I would caution against that for readability – a floating piece of code like that is never pleasant, and in Swift it looks like a labeled block rather than a second parameter to the Button
initializer.
Other Changes in Swift 5.3
Multi-pattern catch clauses | Changes in Swift 5.3
Multi-pattern catch clauses
Synthesized Comparable conformance for enums | Changes in Swift 5.3
Synthesized Comparable conformance for enums
self is no longer required in many places | Changes in Swift 5.3
self is no longer required in many places
Type-based program entry points | Changes in Swift 5.3
Type-based program entry points
where clauses on contextually generic declarations | Changes in Swift 5.3
where clauses on contextually generic declarations
Enum cases as protocol witnesses | Changes in Swift 5.3
Enum cases as protocol witnesses
Refined didSet semantics | Changes in Swift 5.3
Refined didSet semantics
A new Float16 type | Changes in Swift 5.3
A new Float16 type
Swift Package Manager gains binary dependencies, resources, and more | Changes in Swift 5.3
Swift Package Manager gains binary dependencies, resources, and more