Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: How to call a function from a different swift file

Tags:

ios

swift

xcode6

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.

like image 698
user3737262 Avatar asked Jun 26 '14 10:06

user3737262


2 Answers

You should create instance of LoginScreen first and call method on that object:

let login = LoginScreen()
var userType = login.checkPrivs()
like image 184
Greg Avatar answered Nov 15 '22 00:11

Greg


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.

like image 36
Trev14 Avatar answered Nov 14 '22 23:11

Trev14