Swift报错:无法将'() -> _'类型的值转换为指定类型'BLTNItemManager'问题求助
解决BLTNItemManager类型转换错误的问题
嘿,我一眼就看到问题出在哪啦!你遇到的这个类型转换错误,其实是个很常见的Swift闭包小疏忽~
错误原因
你定义boardManager这个懒加载属性时,用闭包来初始化,但最后少加了一对执行括号!Swift现在把这个闭包当成了一个() -> BLTNItemManager的函数类型,而不是直接执行闭包返回BLTNItemManager实例,所以才会报Cannot convert value of type '() -> _' to specified type 'BLTNItemManager'的错误。
修正后的代码
只需要在闭包的末尾加上(),让Swift执行这个闭包并返回实例:
private lazy var boardManager: BLTNItemManager = { let item = BLTNPageItem(title: "Push Notifications") item.image = UIImage(named: "Bell") item.actionButtonTitle = "Continue" item.alternativeButtonTitle = "Maybe Later" item.descriptionText = "Would you like to stay in the loop and get notifications?" item.actionHandler = { _ in ViewController.didTapBoardContinue() } item.alternativeHandler = { _ in ViewController.didTapBoardSkip() } return BLTNItemManager(rootItem: item) }() // 这里补上括号!
额外小提示
另外顺便提一句:你在handler里调用的ViewController.didTapBoardContinue()和didTapBoardSkip(),如果这两个是实例方法的话,直接用类名调用会报错,得改成用当前实例(比如self.didTapBoardContinue(),不过在闭包里要注意循环引用,建议加上[weak self]);如果是类方法的话就没问题啦。
内容的提问来源于stack exchange,提问作者Newbie Swift Coder
相关产品推荐
相关产品推荐

