Swift中的可选闭包属性

Swift中的可选闭包属性

本文介绍了Swift中的可选闭包属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Swift中将可选闭包声明为属性?

How do you declare an optional closure as a property in Swift?

我正在使用此代码:

    var respondToButton:(sender: UIButton) -> Bool

但编译器抱怨该属性未在初始化程序结束时初始化。我相信我可以通过将var声明为可选来解决此问题,但是,我找不到正确的语法。

but the compiler complains that the property is not initialized by the end of the initializer. I believe I can solve this issue by declaring the var as an optional, however, I can not find the correct syntax.

如何将此闭包属性声明为可选项?

How do I declare this closure property as an optional?

推荐答案

我相信你只需要在括号中包含闭包类型,如下所示:

I believe you just need to wrap the closure type in parenthesis, like so:

var respondToButton:((sender: UIButton) -> Bool)?






或者,如果这是封闭类型,那么你就是经常使用你可以创建使其更具可读性:


Alternatively if this is a closure type you're going to use often you can create a typealias to make it more readable:

typealias buttonResponder = (sender: UIButton) -> Bool

然后在你的班级:

var respondToButton:buttonResponder?

这篇关于Swift中的可选闭包属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 04:21