[英]Swift: Access an enum from another viewController class
I have two viewcontrollers (A and B).我有两个视图控制器(A 和 B)。 In main viewcontroller (A) I'm trying to set a variable and the possible values are enums.
在主视图控制器 (A) 中,我试图设置一个变量,可能的值是枚举。 The following code is in second viewcontroller(B)
以下代码在第二个视图控制器(B)中
Code:代码:
enum Numbers: String {
case one = "One"
case two = "two"
case three = "three"
}
var numberSelected: Numbers? = .one
I'm trying to load the second ViewController(B) and set numberSelected with the value depending on selection in the Main viewController:我正在尝试加载第二个 ViewController(B) 并根据 Main viewController 中的选择设置 numberSelected 的值:
func loadSecondoViewController() {
let storyBoard = self.storyboard?.instantiateViewController(withIdentifier: "ColorsViewController")
guard let secondVC = storyBoard as? SecondViewController else {return}
secondVC.modalTransitionStyle = UIModalTransitionStyle.flipHorizontal
switch languageSelected {
case .one:
secondVC.numberSelected = secondVC.
self.present(secondVC, animated: true, completion: nil)
}
On this line:在这一行:
secondVC.numberSelected = secondVC.
I can not access Numbers (enums).我无法访问数字(枚举)。
Anyone know how can we set numberSelected from the main viewcontroller?任何人都知道我们如何从主视图控制器中设置 numberSelected ?
I really appreciate your help.我真的很感谢你的帮助。
You cannot access Numbers
because enums nested in classes are static
.您无法访问
Numbers
因为嵌套在类中的枚举是static
。 You can't access static members through an instance of that class.您不能通过该类的实例访问静态成员。 You can access it normally like this:
您可以像这样正常访问它:
secondVC.numberSelected = SecondViewController.Numbers.one
In fact, you can just write:事实上,你可以只写:
secondVC.numberSelected = .one
If the type of languageSelected
is also SecondViewController.Numbers
, you can do this in one line, without a switch statement:如果
languageSelected
的类型也是SecondViewController.Numbers
,则可以在一行中执行此操作,无需 switch 语句:
secondVC.numberSelected = languageSelected
在任何其他类(如常量类)中创建枚举,并且您想要在哪个类中使用枚举只需创建该枚举的对象并与该对象一起使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.