Swift 2中对成员的歧视性引用

时间:2016-04-01 17:55:41

标签: swift alamofire

我想创建一个通用的网络操作类来处理与我的服务器的通信。我测试了一些东西,错误必须是responseArray函数。但我不知道在哪里?

    class NetworkOperation<T> {
        let requestType: NSMutableURLRequest
        var arrayItems: Array<T>?

        typealias JSONDictionaryCompletion = ([String:AnyObject]?) -> Void
        typealias ObjectArrayCompletion = (Response<[T], NSError>) -> Void

        init(requestType: NSMutableURLRequest, arrayItems: Array<T>) {
            self.requestType = requestType
            self.arrayItems = arrayItems
        }

        func downloadJSONFromURL(completion: JSONDictionaryCompletion) {

        }

        func downloadObjectsFromURL(completion: ObjectArrayCompletion) {
            Alamofire.request(requestType).responseArray { (response) in
                if let httpResponse = response, let statusCode = httpResponse.response {
                    switch(statusCode) {
                    case 200:
                        print("OK")
                    }
                }
            }
        }
    }

extension Alamofire.Request {
    // responseObject<...>(...) declares a new .responseX handling function on Alamofire.Request. It uses the responseSerializer as a custom serializer.
    // The <T> means this is a genertic method: it can work with different types of objects. These types must implement the ResponseJSONObjectSerializable protocol.
    // This is needed to guarantee that any type of object that will be passed in will have an init function that takes JSON. The response function takes a single
    // argument called completionHandler. This is the method being called when done parsing the JSON and creating the object to be called async.
    // The completion handler has a single argument Response<T, NSError>. The response object packs up the Result along iwth all the other info from the transaction.
    // The responseObject function returns an Alamofire.Request object

    public func responseObject<T: ResponseJSONObjectSerializable>(completionHandler: Response<T, NSError> -> Void) -> Self {

        // Create the response serilaizer that will work with the generic T type and an NSError. It will take in the results of the URL Request (request, response, data, error)
        // and use the Result type defined by Alamofire to return success with the object or failure with an error. The responseObject just returns the responseserializer that gets created
        // and allows passing the completion handler where it needs to go.

        let serializer = ResponseSerializer<T, NSError> { (request, response, data, error) in

            // Checks that it has valid data using guard. Then it turns the data into JSON and parses it using SwiftyJSON.
            // Then it creates a new copy of the type of class.

            guard error == nil else {
                return .Failure(error!)
            }

            guard let responseData = data else {
                let failureReason = "Object could not be serialized because input data was nil."
                let error = Error.errorWithCode(.DataSerializationFailed, failureReason: failureReason)
                return .Failure(error)
            }

            let JSONResponseSerializer = Request.JSONResponseSerializer(options: .AllowFragments)
            let result = JSONResponseSerializer.serializeResponse(request, response, responseData, error)

            switch result {
            case .Success(let value):
                let json = SwiftyJSON.JSON(value)
                // Get Data content of JSON
                let jsonData = json["data"]

                if let object = T(json: jsonData) {
                    return .Success(object)
                } else {
                    let failureReason = "Object could not be created from JSON."
                    let error = Error.errorWithCode(.JSONSerializationFailed, failureReason: failureReason)
                    return .Failure(error)
                }
            case .Failure(let error):
                return .Failure(error)
            }
        }
        return response(responseSerializer: serializer, completionHandler: completionHandler)
    }

    // Iterate through the elements in the json and create object out of each one and add it to the objects array.

    public func responseArray<T: ResponseJSONObjectSerializable>(completionHandler: Response<[T], NSError> -> Void) -> Self {
        let serializer = ResponseSerializer<[T], NSError> { request, response, data, error in

            guard error == nil else {
                return .Failure(error!)
            }

            guard let responseData = data else {
                let failureReason = "Array could not be serialized because input data was nil."
                let error = Error.errorWithCode(.DataSerializationFailed, failureReason: failureReason)
                return .Failure(error)
            }

            let JSONResponseSerializer = Request.JSONResponseSerializer(options: .AllowFragments)
            let result = JSONResponseSerializer.serializeResponse(request, response, responseData, error)

            switch result {

            case .Success(let value):
                let json = SwiftyJSON.JSON(value)

                // Get Data content of JSON
                let jsonData = json["data"]

                var objects: [T] = []
                for (_, item) in jsonData {
                    if let object = T(json: item) {
                        objects.append(object)
                    }
                }
                return .Success(objects)

            case .Failure(let error):
                return .Failure(error)
            }
        }
        return response(responseSerializer: serializer, completionHandler: completionHandler)
    }
}

但是当我想检查downloadObjectsFromURL函数中的状态代码时,我收到编译器错误消息:

  

Ambigious对成员请求的引用(:parameters:encoding:headers:)'

此错误来自何处。我是否以错误的方式打开选项?

更新

我测试了这个:

func createObjectsFromJSON(completion: ObjectArrayCompletion) {
    Alamofire.request(requestType).responseArray { (response: Response<[AED], NSError>) -> Void in
        print("OK")
    }
}

AED是我创建的自定义类。没有错误消息了。当我将AED切换为T时会弹出此错误

func createObjectsFromJSON(completion: ObjectArrayCompletion) {
    Alamofire.request(requestType).responseArray { (response: Response<[T], NSError>) -> Void in
        print("OK")
    }
}
  

预期参数类型响应&lt; [_],NSError&gt; - &GT;空隙

0 个答案:

没有答案