Post

Replies

Boosts

Views

Activity

Please help me understand “Finding the Dynamic Type in a Generic Context”
Please help me understand this section! I'm reading Finding the Dynamic Type in a Generic Context that has this snippet: func printGenericInfo<T>(_ value: T) { let t = type(of: value) print("'\(value)' of type '\(t)'") } protocol P {} extension String: P {} let stringAsP: P = "Hello!" printGenericInfo(stringAsP) // 'Hello!' of type 'P' ... that's followed up by this sentence: This unexpected result occurs because the call to type(of: value) inside printGenericInfo(_:) must return a metatype that is an instance of T.Type , but String.self (the expected dynamic type) is not an instance of P.Type (the concrete metatype of value). 1. How come String.self is not an instance of P when I can run this code? func f(_ t: P.Type) { print("...") } f(String.self) 2. Why does type(of:) return the concrete metatype outside but not inside generic functions? print("'\(stringAsP)' of type '\(type(of: stringAsP))'") // 'Hello!' of type 'String'
1
0
335
Feb ’24
What is the name of this technique/pattern?
I notice that this pattern shows up quite frequently in the Swift world but I don't know what its name is. define a new type that conforms to a protocol solely use the new type as a unique value to create a new "thing" extension VerticalAlignment { struct CustomAlignment: AlignmentID {...} static let customAlignment = VerticalAlignment(CustomAlignment.self) }
0
0
286
Feb ’24
SWIFTUI 2, SWIFTUI 3 - MACOS: Why TextField's onCommit closure is always trigger every time I switch to another tab
My code: I use onCommit closure to be able to perform an action by pressing the Enter key when the TextField is being focused. import SwiftUI struct ContentView: View { @State private var text = "" var body: some View { TabView { TextField( "", text: $text, onCommit: { print("onCommit") } // I have a problem here ) .tabItem { Text("Tab 1") } Text("Tab 2") .tabItem { Text("Tab 2") } Text("Tab 3") .tabItem { Text("Tab 3") } } } } My problem: The onCommit closure is also always triggered when I switch to another tab, making my App perform an unexpected action. My questions: This is the bug or the feature? Is there any other way to perform an action by pressing Enter key?
1
0
505
Jun ’21