This works, but unnecessarily exposes T
in Unwrap
's generic parameters.
import SwiftUI
struct Unwrap<T, Content>: View where Content: View {
let body: Content
init(value: T?, @ViewBuilder ifSome: (T) -> Content, @ViewBuilder ifNone: () -> Content) {
if let value = value {
self.body = ifSome(value)
} else {
self.body = ifNone()
}
}
}
extension Unwrap where Content == AnyView {
init<SomeContent, NoneContent>(value: T?, @ViewBuilder ifSome: (T) -> SomeContent, @ViewBuilder ifNone: () -> NoneContent) where SomeContent: View, NoneContent: View {
self.init(value: value, ifSome: { value in AnyView(ifSome(value)) }, ifNone: { AnyView(ifNone()) })
}
}
This doesn't expose T
but the compiler complains that the extension is ambiguous.
import SwiftUI
struct Unwrap<Content>: View where Content: View {
let body: Content
init<T>(value: T?, @ViewBuilder ifSome: (T) -> Content, @ViewBuilder ifNone: () -> Content) {
if let value = value {
self.body = ifSome(value)
} else {
self.body = ifNone()
}
}
}
extension Unwrap where Content == AnyView {
init<T, SomeContent, NoneContent>(value: T?, @ViewBuilder ifSome: (T) -> SomeContent, @ViewBuilder ifNone: () -> NoneContent) where SomeContent: View, NoneContent: View {
// ERROR: Ambiguous use of 'init(value:ifSome:ifNone:)'
self.init(value: value, ifSome: { value in AnyView(ifSome(value)) }, ifNone: { AnyView(ifNone()) })
}
}