2

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.

jayess
  • 49
  • 6
user2924482
  • 8,380
  • 23
  • 89
  • 173

2 Answers2

3

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
Sweeper
  • 213,210
  • 22
  • 193
  • 313
0

Create enum in any other class like constant class and in which class you wAnt to use enum just create object of that enum and use with that object.

Anil Kumar
  • 1,830
  • 15
  • 24
  • Can you post and example? – user2924482 Aug 08 '18 at 01:33
  • this is your enum: enum checkUSerType : String{ case kSignUpUser = "signUp" case kLoginUser = "Login" } Create Object in using class var userType = checkUSerType.kLoginUser – Anil Kumar Aug 08 '18 at 01:37
  • create object or same enum in another class and from segue or object just set the value you want assign destinationVC.userType = userType == checkUSerType.kSignUpUser ? .kSignUpUser : .kLoginUser – Anil Kumar Aug 08 '18 at 01:46