'How to call a function from a different swift file
I have multiple swift files of type UIViewController in my Xcode 6 beta-2 project.
I basically want to know some data from file A to use in file B.
My files are both UIViewControllers, and I have created a function with no parameters which returns a string in UIViewController_A. When I try and call said function in UIViewController_B, intellisense fills it out for me but says I have to have a parameter which autofills as UIViewController_A).
In the code, LoginScreen.swift == ViewController_A, and ViewResidentsTask == ViewController_B.
My function is called checkPrivs, exists in LoginScreen.swift and looks like this:
func checkPrivs()-> String{
return userPrivType
}
this is how I think it should be called:
var userType = LoginScreen.checkPrivs()
this is what intellisense does when I try and call it:
var userType = LoginScreen.checkPrivs(LoginScreen)
This throws up an error saying "Expected ',' seperator" Not really sure what I should be replacing LoginScreen with but everything I've tried (empty, string, current file name) throws up an error.
Solution 1:[1]
You should create instance of LoginScreen first and call method on that object:
let login = LoginScreen()
var userType = login.checkPrivs()
Solution 2:[2]
Swift 3
Super simple answer - all you have to do is initialize the view controller with () like this:
var userType = LoginScreen().checkPrivs()
This is working for me as of 5/11/17 in the newest version of Xcode & Swift.
Solution 3:[3]
It’s simple! Just put “public” before “Func”
Public func sayhi(){ Print(“hi”) }
Although this doesn’t work in all places. Try it out in a playground first to understand!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Greg |
Solution 2 | Trev14 |
Solution 3 | Obaloluwa Adejuwon |