GarySabo
GarySabo

Reputation: 6710

accessing property from another viewController's class in Swift?

Working with a split view controller...I have a variable that gets a value in my settingsViewController class, and now in my main view controller I need to access the valuable that variable. How can I get to settingsViewController.selectedCounty?

class settingsViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {

 let titleData = TitleData()
 var selectedCounty = String?("Allegany")

trying to grab this value to place in:

class ViewController: UIViewController {


let settings = settingsViewController()
let selectedCounty = settings.selectedCounty

returns "settingsViewController.type" does not have a member named selectedCounty?

enter image description here

Upvotes: 1

Views: 6709

Answers (3)

PANKAJ VERMA
PANKAJ VERMA

Reputation: 3610

In Swift initial value of a (stored)property can not be dependent on other property(s). Here your ViewController's property(i.e. selectedCounty) depends on settingsViewController's property(i.e. selectedCounty).

Solution: You can assign it later in init()

let selectedCounty:String

init(){

selectedCounty = settings.selectedCounty!

}

Upvotes: 0

GarySabo
GarySabo

Reputation: 6710

I ended up figuring it out, I needed to call prepareForSegue on settingsViewController to be able to pass this to my other ViewController (note I changed it to FirstViewController to avoid confusion:

   override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    var destViewController: FirstViewController = segue.destinationViewController as! FirstViewController
    destViewController.selectedCounty = selectedCounty
}

Upvotes: 2

Wojtek Surowka
Wojtek Surowka

Reputation: 21013

The line

let settings = settingsViewController()

creates a constant of the name settings of type settingsViewController. Then in the line

let selectedCounty = settingsViewController.selectedCounty

this constant is not accessed. Rather a type property selectedCounty of the type settingsViewController is accessed. Since there is no such type property, this is an error.

Access the property as follows:

let selectedCounty = settings.selectedCounty

or make it a type property:

Upvotes: -1

Related Questions