Crab asks about @escaping:
Can someone give me an example for this case?
...snip... I'm interested how it would look like.
Create a new project and paste the following example. Please study and report back what you learned.
// EscapingClosureView.swift
// Created by Obelix on 5/6/22.
import SwiftUI
// Day 35 Hint
// If you intend to pass a closure into a view’s initializer for later use,
// Xcode will force you to mark it as @escaping.
// This means “will be used outside of the current method.”
struct SortedBeatles: View {
var sortDirection: (String, String)->Bool // <- Tell me how to sort
var liverpoolLads: [String] // <- Tell me what to sort
// pass a closure into a view's initializer
// I need a closure that takes two Strings, and returns a Bool
// Where are these defined? In the other view, not here.
// They are "packaged" with the closure. They "escaped" the previous struct!
init(direction: @escaping (String, String)->Bool, performers: [String]) {
sortDirection = direction
liverpoolLads = performers
}
var body: some View {
ForEach( liverpoolLads.sorted(by: sortDirection), id:\.self) { Text( $0 ) }
}
}
struct EscapingClosureView: View {
// Define two closures. Functions we'll use later on.
let sortDecending = { (n1:String, n2:String) in n1 > n2 }
let sortAscending = { (n1:String, n2:String) in n1 < n2 }
let beatles = ["john", "paul", "george", "ringo", "obelix"]
@State private var isAscending = true
var body: some View {
VStack{
Form {
Section("Pre sort") {
ForEach( beatles, id: \.self) { Text($0) }
}
Toggle("Sort Ascending", isOn: $isAscending)
Section("Sorted Beatles") {
// NOTE: Passing in a closure to the view's initializer
SortedBeatles(direction: isAscending ? sortAscending : sortDecending, performers: beatles)
}
}.font(.caption).animation(.easeInOut(duration: 1.0), value: isAscending)
}
}
}