I have a class CommentView
that has an optional closure (for simplification purposes, I’ve cut down the code to its bare basics to make it easy for the reader):
struct CommentView: View
{
@State var enterButtonPushed: ((Comment) -> Void)?
init(enterButtonPushed: @escaping (Comment) -> Void)
{
self.enterButtonPushed = enterButtonPushed
}
var body: some View
{
Button("Enter")
{
if let enterButtonPushed = self.enterButtonPushed
{
enterButtonPushed(Comment())
}
else
{
print("EnterButtonPushed is nil")
}
}
.buttonStyle(.borderedProminent)
}
}
A CommentView
class is created correctly from another class:
CommentView
{
comment in self.reader.comments.append(comment)
}
When I push the enter button, the print statement is indicating that the closure is nil, even though I clearly initialized it with a value. What is the correct way syntactically to declare, instantiate and unwrap an optional closure?