Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing variables from another ViewController in Swift

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? } 
like image 986
fulvio Avatar asked Jun 06 '14 01:06

fulvio


2 Answers

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 
like image 171
Mike Avatar answered Oct 18 '22 03:10

Mike


ViewController1.swift

class ViewController1: UIViewController {      struct GlobalVariable{         static var myString = String()     } } 

ViewController2.swift

class ViewController2: UIViewController  {  print(ViewController1.GlobalVariable.myString)  } 
like image 37
Sabarinathan Jayakodi Avatar answered Oct 18 '22 02:10

Sabarinathan Jayakodi