文件作用域?Swift代理和协议

6

我正在构建一个基于旧Obj-c应用程序的新Swift应用程序。 我目前正在处理代理。

以下是我的.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)

我已经做了很多阅读和研究,所以我认为我基本上是正确的(虽然对swift完全不熟悉...)。但是我遇到了这个错误,“Declaration is only valid in file scope”,出现在 protocol MyAppViewControllerDelegate { 上。我认为这与在类内部声明有关,因此我将其移出,但现在我在类内部的代码中无法识别我声明的委托变量... 有什么想法吗?
2个回答

6
应该是这样的:
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?
}

这样有点局限性,因为它要求你为代理使用一个类,但它可以帮助避免保留循环 :)

2
根据您的源代码,我看到您在类内部声明了协议。 只需在类声明之外声明协议,问题就会解决。
更新: 默认访问级别设置为internal,定义为:
Internal访问允许实体在定义模块中的任何源文件中使用,但不能在该模块之外的任何源文件中使用。通常在定义应用程序或框架的内部结构时使用内部访问。
与Objective-C或C相比,如果实现在使用之前没有发生,您不需要前向声明。
来源:Swift编程语言,访问控制

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接