【问题标题】:How to call the typealias in Swift如何在 Swift 中调用 typealias
【发布时间】:2016-12-23 10:57:17
【问题描述】:

我刚刚开始学习 swift 3,我正在将 Objective-c 中的代码转换为 swift 3,但我被困在 typealias。我已经搜索过了,可能已经有正确的帮助,但它并没有解决我的问题。

这是objective-c中的一行:

typedef void (^TagBlock)(NSString *tagText, NSInteger idx);

并且在objective-c中有一个属性为@property (nullable, copy) TagBlock tapBlock;
现在我将上面的行转换为:

typealias TagBlock = (_ tagText: NSString,_ idx: NSInteger) -> Void

这是我非常了解的语法,属性是 var tapBlock: TagBlock! 在 swift 的情况下。

现在我尝试在 @IBAction 方法之一中调用它:

if (tapBlock != nil) {
    self.setTapBlock(tapBlock: (tagButton.titleLabel?.text,tag) -> Void)
}

这给出了一个错误:

'->'之前的预期类型

目标中的这一行是:

if (_tapBlock) {
    _tapBlock(sender.titleLabel.text, self.tag);
  }



更新import UIKit 之后我添加了typealias TagBlock = ((String, Int) -> Void)? 之后var tapBlock: TagBlock!
class TagView: UIView 中我正在调用@987654333 @as

@IBAction func tagTapped(_ sender: Any) {
    if (tapBlock != nil) {
            tapBlock?(sender.titleLabel.text, self.tag)
        }
    }

所以在tapBlock?(sender.titleLabel.text, self.tag) 它给了我错误:

不能调用非函数类型'TagBlock'的值`

【问题讨论】:

    标签: ios swift3 objective-c-blocks type-alias


    【解决方案1】:

    nullable 在 Swift 中是可选的,在 Swift 3 中不要使用下划线和参数标签。

    等价于:

    typealias TagBlock = ((String, Int) -> Void)?
    

    你可以简单地称呼它

    tapBlock?(sender.titleLabel.text, self.tag)
    

    由于可选链接,如果tapBlocknil,则不会调用闭包。

    【讨论】:

    • 它给出了一个错误Cannot call value of non-function type 'TagBlock'
    • 另一个约定,我提到它是为了完成,是使用Void,其中参数为Void,而(),当返回类型为void。所以另一种选择是typealias TagBlock = ((String, Int) -> ())?
    • @ChaudhryTalha 编辑您的问题并添加导致错误的代码。
    • 由于类型别名已经是可选的,因此您必须声明var tapBlock: TagBlock(不带感叹号)。无论如何从不将可选完成块声明为隐式解包 (!),将它们始终声明为标准可选 (?)。但错误似乎来自其他地方。
    • 通过将 typealias 定义为 (_ tagText: String,_ index: Int) -> Void 来使用“修饰”参数标签并没有错——尽管它们不在调用站点使用,但它们允许作者进行自我记录。跨度>
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多