[英]SWIFT: Is it possible to access stored properties of a class inside its extension?
class BibliothequesViewController: UIViewController {
static let sharedInstance = BibliothequesViewController()
var presentedBy: UIViewController?
}
I tried to access, both sharedInstance
and presentedBy
inside the extension:我试图访问扩展中的
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'
}
}
The first error makes sense.第一个错误是有道理的。
The second one doesn't as I have used BibliothequesViewController.sharedInstance.presentedBy
in other areas in the app and it works fine.第二个没有,因为我在应用程序的其他区域使用了
BibliothequesViewController.sharedInstance.presentedBy
并且它工作正常。
The point is I want to know is there a way to access sharedInstance
or presentedBy
inside the extension?关键是我想知道有没有办法在扩展中访问
sharedInstance
或presentedBy
?
The target of as
is a type, not a variable. as
的目标是一个类型,而不是一个变量。 The only thing you know about presentedBy
is that it's of type Optional<UIViewController>
.你唯一知道的关于
presentedBy
是它是Optional<UIViewController>
类型。 And segue.destination
is of type UIViewController. segue.destination
是 UIViewController 类型。 Since every type can be promoted to the optional of its type, your as
isn't doing anything.由于每种类型都可以提升为其类型的可选类型,因此您的
as
没有做任何事情。 When you're done, you know it's a UIViewController.完成后,您就知道它是一个 UIViewController。 You're good to go.
你很高兴去。 You can call any UIViewController methods you want, but you could do that anyway.
您可以调用任何您想要的 UIViewController 方法,但无论如何您都可以这样做。
In short: your as!
总之:你
as!
isn't doing anything.什么都不做Just get rid of it.
摆脱它。
(As @Runt8 notes, yes, you can definitely access stored properties from an extension, but that has nothing to do with your actual question.) (正如@Runt8 所指出的,是的,您绝对可以从扩展程序访问存储的属性,但这与您的实际问题无关。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.