Your function expects a return value of type UIViewController
and you return nothing. So either return an instance you create (if you need one). Or remove return value.
There's a slightly modified variation of your function with generics, which does just what you want. The @discardableResult
word before the function tells the compiler that the result can be omitted.
@discardableResult
func goToPage<T>(goto storyBoardId: String,
ofType typeUIViewController: T.Type) -> T
where T: UIViewController {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let newPage = storyboard.instantiateViewController(withIdentifier: storyBoardId) as! T
self.present(newPage, animated: true, completion: nil)
return newPage
}
USAGE
// Ignore return value
goToPage(goto: "Page", ofType: ViewController.self)
// Preserve return value:
// Thanks to generics, page and page2 types are inferred by the compiler
// page is CustomController and page2 is LoginController
// and you can access corresponding interface:
var page = goToPage(goto: "Page", ofType: CustomController.self)
var page2 = goToPage(goto: "Page", ofType: LoginController.self)
Update
I see that Honey suggests the right idea, but the problem with typecasting still persists. The reason of that is that the compiler has no idea what kind of type typeUIViewController
is. In fact, it is not actually even a type, it's only an inner name of the variable. And there is no way compiler could infer the type of it (to use with as
operator). Hence, one of the proper ways to achieve what you are trying is by using generics. Consider generic T
as a pattern which meets certain condition.