Я пытался установить else
параметр по умолчанию в методе ifLet
, но я сталкиваюсь с ошибкой: Protocol 'View' can only be used as a generic constraint because it has Self or associated type requirements
. Что сделал не так?
extension View {
func ifLet<Value, Then: View, Else: View>(
_ value: Value?,
then: (Value) -> Then,
else: () -> View = { EmptyView() }
) -> _ConditionalContent<Then, Else> {
if let value = value {
return ViewBuilder.buildEither(first: then(value))
} else {
return ViewBuilder.buildEither(second: `else`())
}
}
}
Использование:
struct TestView: View {
var test: String?
var body: some View {
Group {
ifLet(test) { Text($0) }
ifLet(test, then: { Text($0) }, else: { Text("Empty") })
}
}
}
Лучшее решение без использования неофициального _ConditionalContent
, которое может быть изменено или удалено в будущем. Проверьте здесь