简体   繁体   中英

Swift: Access an enum from another viewController class

I have two viewcontrollers (A and B). In main viewcontroller (A) I'm trying to set a variable and the possible values are enums. The following code is in second viewcontroller(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:

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?

I really appreciate your help.

You cannot access Numbers because enums nested in classes are 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:

secondVC.numberSelected = languageSelected

在任何其他类(如常量类)中创建枚举,并且您想要在哪个类中使用枚举只需创建该枚举的对象并与该对象一起使用。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM