[英]File Scope? Swift Delegates and Protocols
我正在努力構建一個新的Swift應用程序,大致基於一個舊的Obj-c應用程序。 我目前正在為代表們工作
這是我的obj-c代碼在.h文件中的樣子
@interface MyAppViewController : CustomViewController
@property (nonatomic, weak) id<MyAppViewControllerDelegate> delegate;
@end
@protocol MyAppViewControllerDelegate <NSObject>
- (void)myAppViewController:(MyAppViewController *)controller loggedInStudent: (MYStudent *)student;
- (void)myAppViewControllerWantsSignUp:(MyAppViewController *)controller;
@end
在SWIFT我做了:
class MyAppViewController: CustomViewController {
var delegate: MyAppViewControllerDelegate?
protocol MyAppViewControllerDelegate{
func myAppViewController(controller: MyAppViewController, loggedInStudent: MYStudent)
func myAppViewControllerWantsSignUp(controller: MyAppViewController)
我已經做了很多閱讀和研究,所以我認為我做的基本上是正確的(盡管很快,但是......)
我收到此錯誤,“ Declaration is only valid in file scope
”, protocol MyAppViewControllerDelegate {
我認為這與在類中聲明它有關,所以我把它移出來,只是現在我的代碼在類中沒有不承認我聲明的委托變量..
有任何想法嗎?
應該是這樣的:
protocol MyAppViewControllerDelegate {
func myAppViewController(controller: MyAppViewController, loggedInStudent: MYStudent)
func myAppViewControllerWantsSignUp(controller: MyAppViewController)
}
class MyAppViewController: CustomViewController {
var delegate: MyAppViewControllerDelegate?
}
雖然,如果您遵循一個常見模式,其中擁有MyAppViewController
的對象也是其委托,這可能會導致內存問題。 你可以使用class
輸入來允許弱委托,如下所示:
protocol MyAppViewControllerDelegate : class {
func myAppViewController(controller: MyAppViewController, loggedInStudent: MYStudent)
func myAppViewControllerWantsSignUp(controller: MyAppViewController)
}
class MyAppViewController: CustomViewController {
weak var delegate: MyAppViewControllerDelegate?
}
這有點限制,因為它要求您為您的委托使用一個類,但它將有助於避免保留周期:)
從我在源代碼中看到的是你已經在你的類中聲明了你的協議。 只需在類聲明之外聲明協議,你就可以了。
更新:
默認訪問級別設置為internal,定義為
內部訪問使實體可以在其定義模塊的任何源文件中使用,但不能在該模塊之外的任何源文件中使用。 在>定義應用程序或框架的內部結構時,通常使用內部訪問。
與Objective-C或C相比,如果在使用之前沒有發生實現,則不需要前向聲明。
來源: Swift編程語言,訪問控制
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.