在 Swift Xcode 中使用其他文件中的函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28780862/
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
Use functions from other files in Swift Xcode
提问by Erik Lydecker
How can I write a function in a separate swift file and use it (import it) to my ViewController.swift file? I have written a lot of code and all of the code is in the ViewController.swift file, I really need to make this look good and place functions on separate files, for cleaner code. I have functions dealing with parsing HTML, functions dealing with ordering results, presenting results, responding to user actions, etc. Many thanks for any help!
如何在单独的 swift 文件中编写函数并将其使用(导入)到我的 ViewController.swift 文件?我写了很多代码,所有代码都在 ViewController.swift 文件中,我真的需要让它看起来很好,并将函数放在单独的文件中,以获得更清晰的代码。我有处理 HTML 解析的函数,处理排序结果的函数,呈现结果,响应用户操作等。非常感谢您的帮助!
if let htmlString = String(contentsOfURL: checkedUrl, encoding: NSUTF8StringEncoding, error: nil) {
// Parsing HTML
let opt = CInt(HTML_PARSE_NOERROR.value | HTML_PARSE_RECOVER.value)
var err : NSError?
var parser = HTMLParser(html: htmlString, encoding: NSUTF8StringEncoding, option: opt, error: &err)
var bodyNode = parser.body
// Create an array of the part of HTML you need
if let inputNodes = bodyNode?.findChildTags("h4") { //inputNodes is an array with all the "h4" tag strings
for node in inputNodes {
let result = html2String(node.rawContents)
println("Nyheter: \(result)")
}
}
When I add that function to a separate swift file, how can I use it in my ViewDidLoad method using a "shorthand"? A short keyword that grabs that chunk of code and use it?
当我将该函数添加到单独的 swift 文件时,如何使用“简写”在我的 ViewDidLoad 方法中使用它?获取该代码块并使用它的简短关键字?
回答by Teemu Kurppa
Easy. You just create a new Swift file into your Xcode project (File - New - File - Swift fileor just ?-N) and put your functions and classes there. No need to import anything in your view controller file as both files are part of the same package and thus see each others functions and types (unless marked as private).
简单。您只需在 Xcode 项目中创建一个新的 Swift 文件(File - New - File - Swift 文件或仅?-N)并将您的函数和类放在那里。无需在您的视图控制器文件中导入任何内容,因为这两个文件是同一个包的一部分,因此可以看到彼此的功能和类型(除非标记为私有)。
func parseHtml(url: NSURL) -> String { ... your code goes here ... }
回答by Mohammad Nurdin
You need to use singletons
.
您需要使用singletons
.
Create NSObject in User.swift
在中创建 NSObject User.swift
import Foundation
import UIKit
class User: NSObject {
var name: String = 0
func getName() -> String{
name = "Erik Lydecker"
return name
}
}
Then initialize your object and trigger the method there.
然后初始化您的对象并在那里触发方法。
ViewController.swift
视图控制器.swift
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let instanceOfUser = User()
instanceOfUser.getName() // Erik Lydecker
}
}
回答by Zonily Jame
You can create a Utilsclass
, filled with static variables/functions
您可以创建一个Utilsclass
,填充static variables/functions
For example:
例如:
class Utils {
static func convert(to variable: String) -> Int? {
... do some stuff to variable
return newVariable
}
}
// on your ViewController.swift
override func viewDidLoad() {
super.viewDidLoad()
if let converted = Utils.convert(to: "123") {
print(converted)
}
}
By making use of static functions you can access them anywhere and everywhere to reuse them.
通过使用静态函数,您可以随时随地访问它们以重用它们。
------------------
------------------
Another way is to make use of extensions
另一种方法是利用 extensions
For example:
例如:
extension String {
var toInt: Int? {
return Int(self)
}
}
// on your ViewController.swift
override func viewDidLoad() {
super.viewDidLoad()
if let converted = "SomeValue".toInt {
print(converted)
}
}
Both of these can be used in many different scenarios.
这两者都可以用于许多不同的场景。