How to handle Void success case with Result lib (success/failure)

前端 未结 3 2019
Happy的楠姐
Happy的楠姐 2021-01-11 14:49

Introduction:

I\'m introducing a Result framework (antitypical) in some points of my app. In example, given this function:

func find         


        
3条回答
  •  执笔经年
    2021-01-11 15:24

    I found Rob's answer really interesting and smart. I just want to contribute with a possible working solution to help others:

    enum VoidResult {
        case success
        case failure(Error)
    }
    
    /// Performs a request that expects no data back but its success depends on the result code
    /// - Parameters:
    ///   - urlRequest: Url request with the request config
    ///   - httpMethodType: HTTP method to be used: GET, POST ...
    ///   - params: Parameters to be included with the request
    ///   - headers: Headers to be included with the request
    ///   - completion: Callback trigered upon completion
    func makeRequest(url: URL,
                     httpMethodType: HTTPMethodType,
                     params: [String:Any],
                     headers: [String:String],
                     completion: @escaping (VoidResult) -> Void){
        let alamofireHTTPMethod = httpMethodType.toAlamofireHTTPMethod()
        
        let parameterEncoder: ParameterEncoding
        switch alamofireHTTPMethod {
        case .get:
            parameterEncoder = URLEncoding.default
        case .post:
            parameterEncoder = JSONEncoding.default
        default:
            parameterEncoder = URLEncoding.default
        }
        
        Log.d(message: "Calling: \(url.absoluteString)")
        AF.request(url,
                   method: alamofireHTTPMethod,
                   parameters: params,
                   encoding:parameterEncoder,
                   headers: HTTPHeaders(headers)).response { response in
                    guard let statusCode = response.response?.statusCode,
                        (200 ..< 300) ~= statusCode else {
                            completion(.failure(NetworkFetcherError.networkError))
                            return
                    }
                    completion(.success)
                    
        }
        
      }
    

提交回复
热议问题