ios Swift:如何从不同的 Swift 文件调用函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24428426/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Swift: How to call a function from a different swift file
提问by user3737262
I have multiple swift files of type UIViewController in my Xcode 6 beta-2 project.
我的 Xcode 6 beta-2 项目中有多个 UIViewController 类型的 swift 文件。
I basically want to know some data from file A to use in file B.
我基本上想知道文件 A 中的一些数据以在文件 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).
我的文件都是 UIViewControllers,我创建了一个没有参数的函数,它在 UIViewController_A 中返回一个字符串。当我尝试在 UIViewController_B 中调用上述函数时,intellisense 会为我填写它,但说我必须有一个自动填充为 UIViewController_A 的参数)。
In the code, LoginScreen.swift == ViewController_A, and ViewResidentsTask == ViewController_B.
在代码中,LoginScreen.swift == ViewController_A 和 ViewResidentsTask == ViewController_B。
My function is called checkPrivs, exists in LoginScreen.swift and looks like this:
我的函数名为 checkPrivs,存在于 LoginScreen.swift 中,如下所示:
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.
这会引发一个错误,指出“预期的 ',' 分隔符”不确定我应该用什么替换 LoginScreen,但我尝试过的所有内容(空、字符串、当前文件名)都会引发错误。
I'm pretty new to Xcode and from a c# background, any help would be much appreciated.
我对 Xcode 和 ac# 背景很陌生,任何帮助将不胜感激。
ANSWER:Turns out I was declaring 'loginScreen' inside the UIViewController class when I should have been declaring it outside of the class.
答案:结果我在 UIViewController 类中声明了 'loginScreen',而我应该在类之外声明它。
回答by Greg
You should create instance of LoginScreen first and call method on that object:
您应该首先创建 LoginScreen 的实例并在该对象上调用方法:
let login = LoginScreen()
var userType = login.checkPrivs()
回答by Trev14
Swift 3
斯威夫特 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.
截至 2017 年 5 月 11 日,在最新版本的 Xcode 和 Swift 中,这对我有用。