如何解决SWIFT:是否可以在其扩展名内访问类的存储属性?
class BibliothequesViewController: UIViewController {
static let sharedInstance = BibliothequesViewController()
var presentedBy: UIViewController?
}
我尝试访问扩展中的sharedInstance
和presentedBy
:
extension BibliothequesViewController: UITableViewDelegate,UITableViewDataSource {
override func prepare(for segue: UIStoryboardSegue,sender: Any?) {
//Trying to present by using presentBy property
let vc = segue.destination as! presentedBy
// This throws this error: Use of undeclared type 'presentedBy'
let vc = segue.destination as! BibliothequesViewController.sharedInstance.presentedBy
// This throws this error: Static property 'sharedInstance' is not a member type of 'BibliothequesViewController'
}
}
第一个错误是有道理的。
第二个不像我在应用程序的其他区域中使用过BibliothequesViewController.sharedInstance.presentedBy
一样,而且效果很好。
我想知道的是,是否有一种方法可以访问扩展中的sharedInstance
或presentedBy
?
解决方法
as
的目标是类型,而不是变量。您对presentedBy
唯一了解的是它的类型为Optional<UIViewController>
。 segue.destination
的类型为UIViewController。由于每种类型都可以提升为该类型的可选类型,因此您的as
不会做任何事情。完成后,您将知道它是一个UIViewController。你很好您可以调用所需的任何UIViewController方法,但是仍然可以执行该操作。
简而言之:您的as!
没有做任何事情。摆脱它。
(如@ Runt8所指出的,是的,您绝对可以从扩展名访问存储的属性,但这与您的实际问题无关。)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。