Access array in another Swift file

I have an array called result that I created in a file that I named ParseJSON.swift that is called from ViewController.swift, but when I want to access the array in a separate file MyView.swift it says "Use results" unresolved identifiers "

Obviously the problem is that MyView.swift does not have access to the items in ParseJSON.swift, but I was wondering what is the typical solution for this?

In ParseJSON.swift:

var results = [Int]()

      

In MyView.swift:

var rect = DataRectangle<Int>()
rect.data = results << error here

      

+3


source to share


2 answers


don't know what your code structure is, but in general, if you want to access some variables of one file in another:

Here's how you can do it:



//First file
    class ParseJson: NSObject {

        var results: NSArray = ["1", "2", "3", "4", "5"]

    }

//controller    
    class MyView: UIViewController {

       var copiedArray: NSArray = NSArray()

       override func viewDidLoad() {
            super.viewDidLoad()

             var json: ParseJson = ParseJson() //Create object of ParseJson
             copiedArray = json.results        //access class variables
        }}

      

+1


source


Create a separate file named Manager.swift and put this code in it ...

//manager.swift

import Foundation

struct Manager {

static var results = [Int]()


}

      

Clean up the project by pressing Shift + Command + K.



You can now access and change this variable from any view controller. Here's an example.

//viewController.swift
    println(Manager.results)

      

-1


source







All Articles