ferryawijayanto
ferryawijayanto

Reputation: 649

Function to generate UIViewController

I create a function to avoid repeating code to generate UIViewController properties. here is my code

    let searchVC = generateNavigation(with: SearchViewController(), title: "Search", image: #imageLiteral(resourceName: "search"))
    searchVC.store = store
    searchVC.navigationItem.title = "Search"
    searchVC.tabBarItem = UITabBarItem(title: "Search", image: #imageLiteral(resourceName: "search"), tag: 0)

    let favoriteVC = FavoriteViewController()
    favoriteVC.navigationItem.title = "Favorite"
    favoriteVC.tabBarItem = UITabBarItem(title: "Favorite", image: #imageLiteral(resourceName: "favorites"), tag: 1)

    let downloadVC = DownloadViewController()
    downloadVC.navigationItem.title = "Download"
    downloadVC.tabBarItem = UITabBarItem(title: "Download", image: #imageLiteral(resourceName: "downloads"), tag: 2)

    func generateNavigation(with rootViewController: UIViewController, title: String, image: UIImage) -> UIViewController {
    rootViewController.navigationItem.title = title
    let vc = rootViewController
    vc.tabBarItem.title = title
    vc.tabBarItem.image = image
}

My constant properties does not return SearchViewController. since I want to access the store properties inside SearchViewController, while my other constant property as favouritesViewController and downloadViewController

Upvotes: 0

Views: 37

Answers (1)

dktaylor
dktaylor

Reputation: 914

I think what you're asking is if you can have your function that generically generates your function return a properly typed result. If so, you could do this:

func generateNavigation<T>(with rootViewController: T, title: String, image: UIImage) -> T where T: UIViewController {
    rootViewController.navigationItem.title = title
    let vc = rootViewController
    vc.tabBarItem.title = title
    vc.tabBarItem.image = image
    return vc
}

But I think your question needs a bit more detail about what you're trying to do in the generateNavigation function.

Upvotes: 1

Related Questions