Swift 4:将Objective-c转换为Swift时,非标称类型'T'不支持显式初始化 [英] Swift 4: Non-nominal type 'T' does not support explicit initialization when converting Objective-c to Swift

查看:117
本文介绍了Swift 4:将Objective-c转换为Swift时,非标称类型'T'不支持显式初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将Objective-C项目转换为Swift,这是Objective-C中的.h文件之一:

I'm trying to convert an Objective-C project to Swift, here is one of the .h file in Objective-C:

typedef void(^PrintBlock)(HLPrinter *printer);

@interface ShoppingViewController : UIViewController

@property (copy, nonatomic) PrintBlock printBlock;

@end

.m文件中有一个功能:

and in the .m file, there is a function:

HLPrinter *printer = [self getPrinter];

if (_printBlock) {
    _printBlock(printer);
}

这就是我将其转换为Swift的方式:

And this is how I converted it into Swift:

typealias PrintBlock = (_ printer: HLPrinter?) -> Void

但是当我尝试将上面的函数转换为Swift时,尝试声明类型为PrintBlock的变量时出现了'Non-nominal type 'PrintBlock' (aka '(Optional<HLPrinter>) -> ()') does not support explicit initialization'错误:

But when I tried to convert the function above into Swift, I get a 'Non-nominal type 'PrintBlock' (aka '(Optional<HLPrinter>) -> ()') does not support explicit initialization' error when I was trying to declare a variable with type PrintBlock:

let pb = PrintBlock()

我对Objective-C不熟悉,所以我应该如何用_printerBlock将该功能转换为Swift?

I'm not familiar with Objective-C, so how should I convert that function with _printerBlock into Swift?

推荐答案

PrintBlock是闭包的别名.您不能像创建类或结构那样简单地创建实例.您需要为属性分配一个闭包(或函数).

PrintBlock is an alias for a closure. You can't simply create an instance like you would a class or struct. You need to assign a closure (or function) to the property.

Swift代码为:

typealias PrintBlock = (_ printer: HLPrinter?) -> Void

class ShoppingViewController: UIViewController {
    var printBlock: PrintBlock?

    func getPrinter() -> HLPrinter {
        return somePrinter
    }

    func someFunction() {
        if let printBlock = printBlock {
            let printer = getPrinter()
            printBlock(printer)
        }
    }
}

调用代码将类似于:

let vc = ShoppingViewController()
vc.printBlock = { (printer) in
    // do something with printer
}

或者,如果您有功能:

func someFunction(_ printer: HLPrinter) {
}

您可以分配:

vc.printBlock = someFunction

根据您在问题中提供的部分信息,此处有一些假设.

There's a few assumptions in here based on the partial information you have provided in your question.

这篇关于Swift 4:将Objective-c转换为Swift时,非标称类型'T'不支持显式初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆