Views often don't allow optional parameter values, resulting in an error like Initializer 'init(_:)' requires that 'String?' conform to 'StringProtocol'
:
struct Person {
var name : String
}
struct OptionalsExampleView: View {
var person : Person? = Person(name: "Bob")
var body: some View {
VStack() {
Text("Name:")
Text(person?.name)
}
}
}
Unfortunately, as of Xcode 11.4/iOS 13 the if let
statement is not allowed in View Builder blocks, resulting in an error like Closure containing control flow statement cannot be used with function builder 'ViewBuilder'
:
struct OptionalsExampleView: View {
var person : Person? = Person(name: "Bob")
var body: some View {
VStack() {
if let person = person { // <-- not allowed
Text("Name:")
Text(person?.name)
}
}
}
}
(I know that this question has been answered and asked quite a few times. I wrote this question and answered it myself to have a short overview article that's more concise than the existing articles so that I can link to it in places where this question comes up).