久美子
久美子

Reputation: 121

Is there a way to make an enum return a UIViewController

Is there a way to make an enum return a UIViewController, not just strings or ints?

enum MyEnum {
    case movie
    case music
    case notes

    var viewController: UIViewController {
        case .movie: return MovieViewController
        case .music: return MusicViewController
        case .notes: return NotesViewController
    }
}

Upvotes: 0

Views: 863

Answers (4)

Hải Kaito
Hải Kaito

Reputation: 1

enum MyEnum {
    case movie
    case music
    case notes

    var viewControllerType: UIViewController.Type {
        case .movie: return MovieViewController.self
        case .music: return MusicViewController.self
        case .notes: return NotesViewController.self
    }
}

I think this is what you're meaning for :D Hope to help!!! :D

I had made some utils. Feel free to check it at https://github.com/haiphamthanh/Challenges/blob/other_tableview_layouts/DesignPatterns/AppStoryboard.swift

Upvotes: 0

Masroor
Masroor

Reputation: 86

 enum Storyboard : String {
    case main               = "Main"

/// This function returns controller instance of specified storyboard. Please set same name for storyboard identifier otherwise application will crash.
/// - Parameter name: Controller Name
func controller<T : UIViewController>(_ name : T.Type) -> T {
    let controller = UIStoryboard.init(name: self.rawValue, bundle: nil).instantiateViewController(withIdentifier: "\(name)")
    return controller as! T
  }
}
 //Call it like this where you need this
let controller = Storyboard.home.controller(LoginViewController.self)

While using storyboard and generics you can also create enum like this and get your desired controller from your desired storyboard.

Upvotes: 0

Feridun Erbaş
Feridun Erbaş

Reputation: 654

  1. Make sure MovieViewController is inherited from UIViewController
  2. Make sure you import UIKit in your enum class file

Note: You should not have UIKit components in your models.

Upvotes: 1

Rob
Rob

Reputation: 2164

Yes, you can do this:

enum MyEnum {
case movie
case music
case notes

var viewController: UIViewController {
    
    switch self {
  
    case .movie: return MovieViewController()
    case .music: return MusicViewController()
    case .notes: return NotesViewController()
    default: break
  }
 }
}

Upvotes: 2

Related Questions