0

How do I go about passing a Type as a variable in Swift 4?

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "MapViewController") as! MapViewController

I have something similar to the above in a horrible if statement I'd like to move to a function, but not sure how I pass 'MapViewController' (or whatever the controller is as a variable).

'"Pseduo" Code'

function setVC(withViewController : Any) {
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let vc = storyboard.instantiateViewController(withIdentifier: "MapViewController") as! withViewController
}
Lorenzo B
  • 33,216
  • 24
  • 116
  • 190
Scott Robinson
  • 583
  • 1
  • 7
  • 23
  • Why do you need that? Why do you have to do "as" ? They should all inherits from `UIViewController`. – Larme Jan 22 '18 at 14:18
  • You sir make a very good point. It works without... (I'm still getting my head around certain things - That was a mish-mash of a few tutorials). What use case would there be to specify 'as' manually? – Scott Robinson Jan 22 '18 at 14:21
  • 1
    Because you want to set some properties of your VC (knowing its classes, and so its public properties). – Larme Jan 22 '18 at 14:22
  • Possibly helpful: https://stackoverflow.com/questions/33200035/return-instancetype-in-swift. – Martin R Jan 22 '18 at 14:23

1 Answers1

0

You could use generic parameters like here:

function setVC<T>(withViewController: T) {
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let vc = storyboard.instantiateViewController(withIdentifier: "MapViewController") as! T
}
Kingalione
  • 4,237
  • 6
  • 49
  • 84
  • 1
    Actually such as solution was already suggested in this answer https://stackoverflow.com/a/33200294/1187415 to the question that I linked to above :) – Martin R Jan 22 '18 at 15:02
  • Oh sorry didn't checked the comments. Yes thats the way how it works. – Kingalione Jan 22 '18 at 15:03