在 IOS Swift 中将可重用功能放在哪里?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30633408/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 06:12:50  来源:igfitidea点击:

Where to put reusable functions in IOS Swift?

iosswift

提问by Alex Lacayo

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?

IOS 编程新手,但只是想知道在哪里放置我将在整个代码中使用的函数的最佳位置。例如,我想编写一些函数来执行对 Web 服务的 POST 请求并返回字典。也许是另一个函数来做一些计算。最好创建另一个 .swift 文件并将我的所有功能放在那里。如果是这样,给文件起什么名字比较好?

public func postRequest() -> [String:String] {
     // do a post request and return post data
     return ["someData" : "someData"]
}

回答by Icaro

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"]
    }
}

Now every time you need to use postRequestyou can just use like so: Helper.postRequest()

现在每次需要使用时postRequest都可以这样使用:Helper.postRequest()

I hope that helps you!

我希望对你有帮助!

回答by Dennis

I usually create a separate class if I have functions that will be used by multiple classes, especially for the ones involving network operations.

如果我的函数将被多个类使用,我通常会创建一个单独的类,尤其是那些涉及网络操作的类。

If you just have separate functions that will be used, you can simply create static functions inside that class so it is easily accessible by other classes in a static way:

如果您只有将要使用的单独函数,您可以简单地在该类中创建静态函数,以便其他类以静态方式轻松访问它:

class DataController {
    static func getData() -> [String:String] {
        // do some operations
        return ["someData" : "someData"]
    }
}

let data = DataController.getData()  // example

However, what often has been the case for me (especially if it involves more complicated operations) was that these network operations needed to establish an initial connection beforehand or required some initial setups, and they also performed asynchronous operations that needed to be controlled. If this is the case and you will often be calling such methods, you might want to create a singleton object that you could use throughout different classes and functions. This way, you could do the initial setup or establish an initial connection just once, and then do the rest as needed with the other functions, instead of doing them every time the function gets called.

但是,我经常遇到的情况(特别是如果涉及更复杂的操作)是这些网络操作需要事先建立初始连接或需要一些初始设置,并且它们还执行需要控制的异步操作。如果是这种情况并且您将经常调用此类方法,则您可能希望创建一个可以在不同类和函数中使用的单例对象。这样,您可以只进行一次初始设置或建立初始连接,然后根据需要对其他函数执行其余操作,而不是每次调用函数时都执行这些操作。

Creating a singleton object is pretty simple in Swift:

在 Swift 中创建一个单例对象非常简单:

class DataController {
    static let sharedInstance = DataController()  // singleton object

    init() {
        // do initial setup or establish an initial connection
    }

    func getData() -> [String:String] {
        // do some operations
        return ["someData" : "someData"]
    }
}

let data = DataController.sharedInstance.getData()  // example

For the name of the class, I usually name it something like DataControlleror DataHelper, but anything that makes sense as a "helper" class would work.

对于类的名称,我通常将其命名为DataControllerDataHelper,但任何对“帮助”类有意义的东西都可以使用。

Hope this helps :)

希望这可以帮助 :)

回答by Raymond

For reusable functions it depends what I decide to use. For this specific case I use a separate file, because posting to a backend will become more complicated when the application evolves. In my app I use a backend class, with all kinds of helper classes:

对于可重用的功能,这取决于我决定使用什么。对于这种特殊情况,我使用了一个单独的文件,因为随着应用程序的发展,发布到后端会变得更加复杂。在我的应用程序中,我使用了一个后端类,以及各种辅助类:

struct BackendError {
    var message : String
}

struct SuccessCall {
    var json : JSON

    var containsError : Bool {
        if let error = json["error"].string {
            return true
        }
        else {
            return false
        }

    }
}

typealias FailureBlock  = (BackendError) -> Void
typealias SuccessBlock  = (SuccessCall) -> Void

typealias AlamoFireRequest = (path: String, method: Alamofire.Method, data: [String:String]) -> Request
typealias GetFunction = (path: String , data: [String : String], failureBlock: FailureBlock, successBlock: SuccessBlock) -> Void

class Backend {
   func getRequestToBackend (token: String )(path: String , data: [String : String], failureBlock: FailureBlock, successBlock: 

}

For other cases I often use extensions on Swift classes. Like for getting a random element from an Array.

对于其他情况,我经常在 Swift 类上使用扩展。就像从数组中获取随机元素一样。

extension Array {
    func sampleItem() -> T {
        let index = Int(arc4random_uniform(UInt32(self.count)))
        return self[index]
    }
}

回答by Suryakant Sharma

This very old question but I would like to chirp some more points. There are a few option, basically you can write your utility functions in Swift -

这个非常古老的问题,但我想补充一些要点。有几个选项,基本上你可以在 Swift 中编写你的实用函数 -

A class with static function. For example

具有静态功能的类。例如

class CommonUtility {
      static func someTask() {
      }    
}
// uses
CommonUtility.someTask()

Also, you can have class method's as well instead of static method but those functions can be overridden by subclasses unlike static functions.

此外,您也可以使用类方法而不是静态方法,但与静态函数不同,这些函数可以被子类覆盖。

class CommonUtility {
      class func someTask() {
      }    
}
// uses
CommonUtility.someTask()

Secondly, you can have Global functions as well, that are not part of any class and can be access anywhere from your app just by name.

其次,您也可以拥有全局函数,这些函数不属于任何类,并且可以通过名称从您的应用程序的任何地方访问。

func someTask() {
} 

Though, selecting one over other is very subjective and I thing this is ok to make a class with staticfunction in this particular case, where you need to achieve networking functionality but if you have some functions which perform only one task than Globalfunction is a way to go because Globalfunctions are more modular and separate out single tasks for a single function.

虽然,选择一个而不是另一个是非常主观的,我认为static在这种特殊情况下创建一个具有功能的类是可以的,在这种情况下,您需要实现网络功能,但是如果您有一些功能只执行一项任务,那么Global功能是一种方法go 因为Global函数更加模块化,并且为单个函数分离出单个任务。

In case of staticfunctions, if we access one of the static member, entire class gets loaded in memory. But in case of global function, only that particular function will be loaded in mem

static函数的情况下,如果我们访问静态成员之一,整个类将被加载到内存中。但是在全局函数的情况下,只有那个特定的函数会被加载到 mem 中

回答by cheeseRoot

You can create a separate swift class, might name it WebServicesManager.swift, and write all methods related to web requests in it.

您可以创建一个单独的 swift 类,可以将其命名为WebServicesManager.swift,并在其中编写与 Web 请求相关的所有方法。

You can use class methods, or singleton pattern to access the methods.

您可以使用类方法或单例模式来访问这些方法。