Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: is it possible to use generic and storyboard for UIViewController

let's say, I have UIViewController subclass:

class InformationServiceMenuVC <T : InformationServiceItemProtocol>: UITableViewController {

}

normally I can create instance of view controller by calling something like:

let vc = InformationServiceSideMenuVC<InformationServiceMenuItem>()

but how do I pass needed generic type when use storyboard?

like image 300
iiFreeman Avatar asked Jul 08 '14 13:07

iiFreeman


People also ask

Can you combine swift UI with storyboard?

The answer is YES! Here we will be discussing a simple way to use SwiftUI into our existing project, which already consists of a storyboard. Let's dive in then!

What is UIViewController in Swift?

The UIViewController class defines the shared behavior that's common to all view controllers. You rarely create instances of the UIViewController class directly. Instead, you subclass UIViewController and add the methods and properties needed to manage the view controller's view hierarchy.


2 Answers

Create a concrete class that inherits from the generic class:

class SpecificInformationServiceMenuVC : InformationServiceMenuVC<Specific> {}

Then you can use the specific subclass as your class type in storyboard.

It might even work to just make a typealias:

typealias SpecificInformationServiceMenuVC = InformationServiceMenuVC<Specific>
like image 122
David Berry Avatar answered Sep 21 '22 16:09

David Berry


In Swift 3.0.1, I was able to refactor from this:

class TagPickerViewController: BaseViewController, HasAppController {
}
extension TagPickerViewController: UITableViewDelegate {
}

to:

class TagPickerViewControllerGeneric<TagViewModelClass: TagPickerViewModel>
    : BaseViewController {
}
class TagPickerViewController: TagPickerViewControllerGeneric<TagPickerViewModel>, 
    HasAppController, UITableViewDelegate {
}

While keeping TagPickerViewController in storyboard/xib. Hope it helps

like image 41
Nicholas Ng Avatar answered Sep 19 '22 16:09

Nicholas Ng