【问题标题】:SWIFT: Is it possible to access stored properties of a class inside its extension?SWIFT:是否可以访问其扩展内的类的存储属性?
【发布时间】:2020-12-23 20:37:09
【问题描述】:
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!之后指定类型而不是变量:let vc = segue.destination as! BibliothequesViewController
  • 但要回答您的问题,是的,您可以从扩展程序访问存储的属性。

标签: ios swift xcode uiviewcontroller tvos


【解决方案1】:

as 的目标是一个类型,而不是一个变量。关于presentedBy,您唯一知道的是它的类型为Optional<UIViewController>segue.destination 是 UIViewController 类型。由于每种类型都可以提升为其类型的可选类型,因此您的 as 没有做任何事情。完成后,您就知道它是一个 UIViewController。你可以走了。你可以调用任何你想要的 UIViewController 方法,但无论如何你都可以这样做。

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

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

【讨论】:

    猜你喜欢
    • 2011-01-10
    • 1970-01-01
    • 2014-12-16
    • 1970-01-01
    • 2016-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多