Alamofire(七)-- 結果封裝Result

引言

在前面,我們提到了DataResponse多了一個result屬性,該屬性的存在,即是存儲了序列化后的數據。result屬性的類型是Result,這篇文章,我們就來說說Result

Alamofire中,我們使用了Response來描述請后的結果,這些結果,經過Alamofire的序列化等特殊處理,得到我們想要的結果。因為得到的數據類型各有不同,我們在序列化后的結果中,如何獲取這些類型不同的數據?

現在,我們需要封裝一個對象,這個對象可以表示出我們想要的任何結果,因此,Result出現了。

Result

定義

常規,看看代碼:

/// Used to represent whether a request was successful or encountered an error.
///
/// - success: The request and all post processing operations were successful resulting in the serialization of the
///            provided associated value.
///
/// - failure: The request encountered an error resulting in a failure. The associated values are the original data
///            provided by the server as well as the error that caused the failure.
public enum Result<Value> {
    case success(Value)
    case failure(Error)

    /// Returns `true` if the result is a success, `false` otherwise.
    public var isSuccess: Bool {
        switch self {
        case .success:
            return true
        case .failure:
            return false
        }
    }

    /// Returns `true` if the result is a failure, `false` otherwise.
    public var isFailure: Bool {
        return !isSuccess
    }

    /// Returns the associated value if the result is a success, `nil` otherwise.
    public var value: Value? {
        switch self {
        case .success(let value):
            return value
        case .failure:
            return nil
        }
    }

    /// Returns the associated error value if the result is a failure, `nil` otherwise.
    public var error: Error? {
        switch self {
        case .success:
            return nil
        case .failure(let error):
            return error
        }
    }
}

因為,在網絡請求的結果中,不外乎就2種結果,要么成功、要么失敗,所以,在這里,Alamofire使用了一個枚舉來定義Result

Result定義中,不論是成功選項還是失敗選項,都為其子選項做了值關聯的,另外,Result還是個泛型。

使用

先來看下這個函數:

/// Adds a handler to be called once the request has finished.
    ///
    /// - parameter options:           The JSON serialization reading options. Defaults to `.allowFragments`.
    /// - parameter completionHandler: A closure to be executed once the request has finished.
    ///
    /// - returns: The request.
    @discardableResult
    public func responseJSON(
        queue: DispatchQueue? = nil,
        options: JSONSerialization.ReadingOptions = .allowFragments,
        completionHandler: @escaping (DataResponse<Any>) -> Void)
        -> Self
    {
        return response(
            queue: queue,
            responseSerializer: DataRequest.jsonResponseSerializer(options: options),
            completionHandler: completionHandler
        )
    }

這個函數的目的是把請求成功的結果序列化為了JSON數據,completionHandler的參數類型為DataResponse<Any>Any就會傳遞給Result

有的人可能會問:數據既然已經解析成了JSON,為什么還要返回Any類型?因為,解析后的數據有可能是數組、也有可能是字典,如果解析后是其他格式的數據,那么解析后就會拋出異常。

從上面Result的定義,我們可以看到,Result還有一些其他的屬性,主要是給我們使用方便提供的。

擴展

前面我們也有接觸過,為了打印出更詳細的信息,擴展了Result,實現了CustomStringConvertibleCustomDebugStringConvertible協議:

// MARK: - CustomStringConvertible

extension Result: CustomStringConvertible {
    /// The textual representation used when written to an output stream, which includes whether the result was a
    /// success or failure.
    public var description: String {
        switch self {
        case .success:
            return "SUCCESS"
        case .failure:
            return "FAILURE"
        }
    }
}

// MARK: - CustomDebugStringConvertible

extension Result: CustomDebugStringConvertible {
    /// The debug textual representation used when written to an output stream, which includes whether the result was a
    /// success or failure in addition to the value or error.
    public var debugDescription: String {
        switch self {
        case .success(let value):
            return "SUCCESS: \(value)"
        case .failure(let error):
            return "FAILURE: \(error)"
        }
    }
}

總的來說,Result的封裝還是挺簡單的,很簡單的封裝,讓我們使用起來特別爽。


常規打廣告系列:
簡書:Alamofire(七)-- 結果封裝Result
掘金:Alamofire(七)-- 結果封裝Result
小專欄:Alamofire(七)-- 結果封裝Result

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容