user1904273
user1904273

Reputation: 4764

Launch and Pass String to Destination View Controller in Swift

I am trying to do the seemingly simple task of passing a string to a viewcontroller with a storyboardid in code but am getting a compiler error: 'View Controller does not have member "myString"'

The destination view controller has the storyboard id:myVC and here is my code to launch it:

  let storyboard = UIStoryboard(name: "secondSB", bundle: nil)
        let destvc = storyboard.instantiateViewController(withIdentifier: "myVC")
        destvc.myString = "mapme"

The viewcontroller is assigned to a class that looks like this:

class myMapViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {
    @IBOutlet weak var mapView: MKMapView!
    var myString:String = ""
   }   

This seems extremely straightforward but then again I am relatively new to Swift. If I take out the line with the error, btw, the VC does launch fine. What could I be missing that is causing this error?

Upvotes: 0

Views: 423

Answers (1)

vadian
vadian

Reputation: 285290

instantiateViewController returns the base class UIViewController, you have to cast the type to your subclass.

Please name classes, structs and enums with starting capital letter

let destvc = storyboard.instantiateViewController(withIdentifier: "myVC") as! MyMapViewController 

Upvotes: 1

Related Questions