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.

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

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.

3 Comments

Can you post and example?
this is your enum: enum checkUSerType : String{ case kSignUpUser = "signUp" case kLoginUser = "Login" } Create Object in using class var userType = checkUSerType.kLoginUser
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.