SWIFT:是否可以在其扩展名内访问类的存储属性?

问题描述

class BibliothequesViewController: UIViewController {
 static let sharedInstance = BibliothequesViewController()
   var presentedBy: UIViewController?
 }

我尝试访问扩展中的sharedInstancepresentedBy

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一样,而且效果很好。

我想知道的是,是否有一种方法可以访问扩展中的sharedInstancepresentedBy

解决方法

as的目标是类型,而不是变量。您对presentedBy唯一了解的是它的类型为Optional<UIViewController>segue.destination的类型为UIViewController。由于每种类型都可以提升为该类型的可选类型,因此您的as不会做任何事情。完成后,您将知道它是一个UIViewController。你很好您可以调用所需的任何UIViewController方法,但是仍然可以执行该操作。

简而言之:您的as!没有做任何事情。摆脱它。

(如@ Runt8所指出的,是的,您绝对可以从扩展名访问存储的属性,但这与您的实际问题无关。)