當 f: A -> B 函數用 .map() 包起來,這時 .map(f) 就會把 A? 轉換成 B?。
因為 Value == Int、Content == Text,所以這個例子的 Unwrap 的完整型別為:Unwrap<Int, Text>。
let value: Int?=1let view =Unwrap(value) {Text("\($0)")// Content == Text}let T =type(of: view)// Unwrap<Int, Text>.Typeprint(T)// Unwrap<Int, Text>print(T.Body.self)// Optional<Text>// ⭐️ use `T.self` to reference the type object itselfT.Body.self== Text?.self// true
/* * #todo : turn it into a modifier ? */importSwiftUI/// # 📦 Unwrap/// unwraps a value (of type `Value`) and turns it /// into `some View` (== `Optional<Content>`).structUnwrap<Value, Content:View>:View {privatelet value: Value?// value to be unwrappedprivatelet turnValueIntoContent: (Value) -> Content// Unwrap(_:then:)// Unwrap(_:) { /* ... */ }init(_value: Value?, @ViewBuilder thenturnValueIntoContent: @escaping (Value) -> Content ) { self.value= value self.turnValueIntoContent = turnValueIntoContent }var body: some View { value.map(turnValueIntoContent)// Optional<Content> }}