有没有一种方法可以自行调用函数而无需重新指定其所有参数?

时间:2019-03-20 02:46:42

标签: swift asynchronous recursion closures completionhandler

如果任何人都可以想到另一种方法来实现我的目标,那么欢迎您提出想法!

为了给您一个想法,我提供了40多种不同的功能,这些功能具有类似于以下的签名:

func getXFromServer(arg1: String, arg2: Int, arg3: Bool, completion: ((MyCustomResponse)->Void)? = nil)
func getYDataFromServer(completion: @escaping (Bool)->Void)
func getZDataFromServer(arg1: Int, completion: @escaping (MyGeneric<MyClass>)->Bool)

有些人有争论,有些人没有争论;有些具有完成处理程序,有些是可选的。各种类型都可以传递。

我正在尝试简化处理服务器响应的过程:目前,它有很多重复的代码,它们执行的几乎都是同一件事,只是参数值和类型不同。

由于这些功能都是异步的,因此我使用完成处理程序来检索服务器数据。我希望所有“重复代码”都包含在一个函数中,我们将其称为handleServerResponse取决于服务器响应的值,我想做更多的异步工作并能够重新执行相同的< em>外部功能

例如:

func getYDataFromServer(completion: @escaping (Bool)->Void)
{
    session.dataTask(with: URLRequest()) { data, response, error in
        handleServerResponse(){ valid   //I want to pass 'getYDataFromServer(completion: completion)' here so that 'handleServerResponse' can determine whether to re-execute it or not, based on the server response

            //do more stuff with Y server data
        }
    }.resume()
}

我目前正在handleServerResponse之外处理重新执行,就像这样:

func getYDataFromServer(completion: @escaping (Bool)->Void)
{
    session.dataTask(with: URLRequest()) { data, response, error in
        handleServerResponse(){ valid
            if !valid
            {
                self.getXYZDataFromServer(){
                    getYDataFromServer(completion: completion)
                }
                return
            }
            //do more stuff with Y server data
        }
    }.resume()
}

这是代码的非常简单的版本,但是正如您所看到的,它可以很快地处理很多重复的代码。

谢谢

1 个答案:

答案 0 :(得分:0)

也许这很有帮助

  func getData(_ args: Any..., completion: @escaping ((Any)->Any)){
print(args)
completion(11)
  }

但是函数类型不能强制转换为Any,您可以考虑使用枚举来混合安全类型。

            var valid: Bool = false
            func getXFromServer(arg1: String, arg2: Int, arg3: Bool, completion: ((String)->Void)? = nil){}

            func getYDataFromServer(completion: @escaping (Bool)->Void){
              //  session.dataTask(with: URLRequest()) { data, response, error in
                //    handleServerResponse(){ valid
                     valid.toggle()
                     print(valid)
                        if  valid
                        {
                            MixGetData.XYZ.run{ MixCompletion.XYZ{ firstY.run{MixCompletion.Y(completion) } }}

                        }
                            else {
                                completion(false)
                            }
                   // }
                  //  }.resume()

            }

            func getZDataFromServer(arg1: Int, completion: @escaping (String)->Bool){}
            func getXYZDataFromServer(completion: @escaping ()->Void){
                completion()
            }

            enum MixCompletion{
                case X(((String)->Void)?)
                case Y((Bool)->Void)
                case Z((String)->Bool)
                case XYZ(()->Void)
            }

            enum MixGetData{
                case X( String, Int, Bool )
                case Y
                case Z(Int)
                case XYZ

                func run(completion: (() -> MixCompletion)? = nil){
                    if (completion == nil) {
                    switch (self) {
                    case let .X(arg1, arg2, arg3) : getXFromServer(arg1: arg1, arg2: arg2, arg3: arg3, completion : nil)
                    case let .Z(arg1) : getZDataFromServer(arg1: arg1, completion: {_ in return false})
                    case .Y : getYDataFromServer(completion: {_ in})
                    case .XYZ : getXYZDataFromServer(completion: {})
                        }}
                    else {
                    switch (self, completion!()) {
                    case (let .X(arg1, arg2, arg3), let .X(comp)): getXFromServer(arg1: arg1, arg2: arg2, arg3: arg3, completion : comp)
                    case (let .Z(arg1), let .Z(comp) ) :    getZDataFromServer(arg1: arg1, completion: comp)
                    case (.Y, let .Y(comp)) :   getYDataFromServer(completion: comp)
                    case (.XYZ, let .XYZ(comp)) :   getXYZDataFromServer(completion: comp)
                    default: break
                        }
                        }
                  }
            }
            let firstY =  MixGetData.Y

            firstY.run()
            firstY.run{MixCompletion.Y{bool in print (bool)}}

另一种方法是使用泛型函数。您也可以将两者结合在一起:

      func getYDataFromServer(completion: @escaping (Bool)->Void){
            //  session.dataTask(with: URLRequest()) { data, response, error in
            //    handleServerResponse(){ valid
            valid.toggle()
            print(valid)
            if  valid
            {
                getData(name: "XYZ", array: "") { getData(name: "Y", array: "", completion: completion)}
            }
            else {
                completion(false)
            }
            // }
            //  }.resume()
        }

        func getData<T>(name: String , array: Any... , completion:  T ){
            switch name {
            case "Y":
                getYDataFromServer(completion: completion as! (Bool)-> Void)
            case "X":
                let arg1 =  array[0] as! String; let arg2 = array[1] as! Int; let arg3 = array[2] as! Bool
                getXFromServer(arg1: arg1, arg2: arg2, arg3: arg3, completion: completion as? (String)-> Void)
            case "Z":
                let arg1 = array[0] as! Int
                getZDataFromServer(arg1: arg1, completion: completion as! (String)-> Bool)
            case "XYZ":
                getXYZDataFromServer(completion: completion as! ()-> Void)
            default:
                break;
            }
        }

        getData(name:  "Y",  array : "", completion:  { bool in print (123) } as (Bool)-> Void )

我知道输入四种以上的类型会很烦。但这是编写安全代码的唯一方法。让我们知道你是否幸运。

如果您只需要完成结果,也许这就是您想要的。

 func handleServerResponse<T, U>(_ alternative :  (T) -> () ,  _ completion : @escaping (U) -> (), _ handler : U , _ terminator : () , _ resValid : Bool){
if  resValid   {
    alternative( completion(handler) as! T )
}
else {
    terminator
}
}


  func getYDataFromServer(completion: @escaping (Bool)->Void){

        response.toggle()


       //  session.dataTask(with: URLRequest()) { data, response, error in


                  handleServerResponse({(a) in getXYZDataFromServer {a
                }},  { (a:  @escaping (Bool)->Void)  in getYDataFromServer(completion: a) }, completion,  completion(true), response)         

             handleServerResponse( { (a)   in getXYZDataFromServer{a}} , {  (a:  @escaping (Bool)->Void)   in getZDataFromServer(arg1: 1, completion: { (s) -> Bool in
                a
               return false
            })}, completion,  completion(true), response)

对我来说很好。