Skip to content

Instantly share code, notes, and snippets.

View mhijack's full-sized avatar
🎯
Focusing

Jianyuan Chen mhijack

🎯
Focusing
View GitHub Profile
func myAutoclosure(auto: @autoclosure @escaping () -> Void) -> () -> Void {
return auto
}
let haha: () -> Void = myAutoclosure(auto: print("haha")) // autoclosure will not be called here even though it looks like we are calling it right away
print("haha should not be called yet")
haha()
print("haha should be called")
// haha should not be called yet
struct ContentView: View {
@State var isReduceLoudnessOn = false
var body: some View {
MarshallSpeaker(maximumVolume: isReduceLoudnessOn ? 70 : 100)
}
}
struct Book: Identifiable {
var name: String
var id: UUID = UUID()
}
struct BookList: View {
var books: [Book]
var body: some View {
List {
struct ContentView: View {
@State var isReduceLoudnessOn = false
var body: some View {
if isReduceLoudnessOn {
MarshallSpeaker(maximumVolume: 70)
} else {
MarshallSpeaker(maximumVolume: 100)
}
}
struct MarshallSpeaker: View {
var maximumVolume: Int = 100
@State var volume: Int = 50
var body: some View {
// UI code
}
public func updateVolume(volume: Int) {
self.volume = volume < maximumVolume ? volume : maximumVolume
struct ContentView: View {
@State var isNightTime = false
var body: some View {
if isNightTime {
Text("Speaker volume is 50")
} else {
Text("Speaker volume is 100")
}
}
struct Book {
var id: String
var name: String
}
struct ContentView: View {
private var books: [Book] = []
var body: some View {
List {
@main
struct BookApp: App {
@StateObject private var store = BookStore()
var body: some Scene {
WindowGroup {
ContentView(store: store) // Clear dependency injection than Singletons
}
}
}
struct EnvironmentContainerView: View {
@State var bookStore = BookStore()
var body: some View {
EnvChildView()
.environmentObject(bookStore) // <- `EnvironmentObject` as a view modifier
}
}
struct EnvChildView: View {
struct BookList: View {
@ObservedObject var store = BookStore() // <- Change to @StateObject or create this else where to solve the issue
var body: some View {
List {
ForEach(store.books, id: \.name) {
Text($0.name)
}
}
}