Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/281.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift 如何在嵌套类之外使用枚举_Swift_Enums - Fatal编程技术网

Swift 如何在嵌套类之外使用枚举

Swift 如何在嵌套类之外使用枚举,swift,enums,Swift,Enums,在我的应用程序中,我使用了一个名为BaseNavigator的类。看起来是这样的: class BaseNavigator { enum Destination { } weak var navigationController: UINavigationController? func navigate(to destination: Destination, completion:((Bool) -> ())? = nil) { l

在我的应用程序中,我使用了一个名为
BaseNavigator
的类。看起来是这样的:

class BaseNavigator {
    enum Destination {

    }

    weak var navigationController: UINavigationController?

    func navigate(to destination: Destination, completion:((Bool) -> ())? = nil) {
        let viewController = makeViewController(for: destination)
        navigationController?.pushViewController(viewController, animated: true)

        completion?(true)
    }
}
let navigator = PreferencesNavigator()
navigator.navigate(to: .general)
现在,我想扩展这个类,例如,我可以创建一个
PreferencesNavigator

class PreferencesNavigator: BaseNavigator {
    enum Destination {
        case general
        case about
    }
}
这将允许我这样使用它:

class BaseNavigator {
    enum Destination {

    }

    weak var navigationController: UINavigationController?

    func navigate(to destination: Destination, completion:((Bool) -> ())? = nil) {
        let viewController = makeViewController(for: destination)
        navigationController?.pushViewController(viewController, animated: true)

        completion?(true)
    }
}
let navigator = PreferencesNavigator()
navigator.navigate(to: .general)

然而,当我试图编译它时,Xcode开始抱怨
Destination
不明确。我如何解决这个问题?

您做错了,因为您没有
导航(在
首选项激活器中导航到:
),所以请执行以下操作:

首选项激活器之外写入枚举

enum Destination {
   case general
   case about
}
像这样继承BaseNavigator

class PreferencesNavigator: BaseNavigator {

}
那么你的代码就可以工作了。简短的回答(IMO)是,如果不将枚举设为私有,你就无法做到这一点,我怀疑这会破坏你的方法。你可以阅读更多关于扩展的内容

我不知道你试图解决的问题,但根据我的初步印象,我建议你通过协议来解决

protocol BaseNavigator {
    func getDestination()
}

然后,只要您有一个符合该协议的类,您就可以调用该方法,如果需要,您可以在协议定义中调整返回类型。

但是我不能让它包含不同的案例,基于它在哪个导航器中实现,对吗?@user4992124:我已经更新了我的答案,请检查代码不应该包含即使是编译,因为
首选项navigator
没有名为
导航
的方法。你确定你不是想从
BaseNavigator
而不是从
NSObject
继承吗?此外,你不应该从
NSObject
继承,除非你有充分的理由这么做,Swift不是Objective-C,类不是不需要从任何基类继承。
PreferencesNavigator
如何成为
BaseNavigator
的扩展?对不起,它应该从
BaseNavigator
继承。我认为@holex的意思是,如果不继承所有属性,就不能称之为继承。不能向n enum。因此,您必须创建一个新的enum,这意味着您必须创建另一个方法来处理它。在这一点上,它仅仅是基本导航器的一个子类。嗯,谢谢。这当然会挫败执行所有这些操作的目的,即防止在所有这些导航器中复制/粘贴代码。