Accessing variables from another ViewController in Swift

fulvio picture fulvio · Jun 6, 2014 · Viewed 68.9k times · Source

I have the following ViewController:

class PageContentViewController: UIViewController {

    var pageIndex: Int

}

How would I access pageIndex from another ViewController?

I need to access pageIndex in this function:

func pageViewController(pageViewController: UIPageViewController!, viewControllerBeforeViewController viewController: UIViewController!) -> UIViewController! {

    //var index: Int
    //index = ?

    NSUInteger index = ((PageContentViewController*) viewController).pageIndex; // in Swift?

    if ((index == 0) || (index == NSNotFound)) {
        return nil;
    }

    index--;

    return [self viewControllerAtIndex:index]; // in Swift?
}

Answer

Mike picture Mike · Jun 6, 2014

Everything by default in swift is public, and thus if you declare something like this:

class SomeViewController: UIViewController {
    var someVariable: SomeType = someValue

    init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
    }
}

You can access it as long as you have an instance of it:

var myCustomViewController: SomeViewController = SomeViewController(nibName: nil, bundle: nil)
var getThatValue = myCustomViewController.someVariable