在IOS Swift中放置可重用功能的位置? [英] Where to put reusable functions in IOS Swift?
问题描述
IOS编程的新手,但只是想知道在我的代码中放置函数的最佳位置。例如,我想编写一些函数来对Web服务执行POST请求并返回字典。也许是另一个做一些计算的功能。是否最好创建另一个.swift文件并将所有功能放在那里。如果是这样,那么给出文件的好名字是什么?
New to IOS programming but just wondering where is the best place to put functions that I would use throughout my code. For example, I want to write a few functions to perform a POST request to a web service and return a dictionary. Maybe another function to do some calculations. Is it best to create another .swift file and put all my functions there. And what would be a good name to give the file if so?
public func postRequest() -> [String:String] {
// do a post request and return post data
return ["someData" : "someData"]
}
推荐答案
最好的方法是使用静态函数创建一个辅助类,如下所示:
The best way is to create a helper class with static functions, like this:
class Helper{
static func postRequest() -> [String:String] {
// do a post request and return post data
return ["someData" : "someData"]
}
}
现在,每当你需要使用 postRequest
时,你可以这样使用: Helper.postRequest()
Now every time you need to use postRequest
you can just use like so: Helper.postRequest()
我希望能帮到你!
这篇关于在IOS Swift中放置可重用功能的位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!