Swift 표준 라이브러리 해석: 프로토콜 편 - Error

4762 단어
Error 협의는 오류 처리를 하는 데 쓰인다.소스 코드는 다음과 같습니다.
public protocol Error {
}

extension Error {
    // 
    public var localizedDescription: String { get }
}

extension Error where Self.RawValue : SignedInteger {
}

extension Error where Self.RawValue : UnsignedInteger {
}

표준 라이브러리에는 오류에 대한 구체적인 정보를 설명하기 위한 읽기 전용 속성이 하나만 제공됨을 알 수 있습니다.그 외에는 다른 방법이 없다.
Apple 공식 추천 매거 유형은 다음과 같다.localizedDescription
잘못된 처리에 관해서 나 자신도 이 방면에 대해 깊이 이해하지 못한다.여기에서 제가 여러분께 Swift's enumerations are well suited to represent simple errors. Create an enumeration that conforms to the Error protocol with a case for each possible error. If there are additional details about the error that could be helpful for recovery, use associated values to include that information.Alamofire류를 소개하고 간접적으로 AFError협의의 용법을 알아보겠습니다.

정의

public enum AFError: Error {
    public enum ParameterEncodingFailureReason {
        case missingURL
        case jsonEncodingFailed(error: Error)
        case propertyListEncodingFailed(error: Error)
    }

    public enum MultipartEncodingFailureReason {
        case bodyPartURLInvalid(url: URL)
        case bodyPartFilenameInvalid(in: URL)
        case bodyPartFileNotReachable(at: URL)
        . . .
    }

    public enum ResponseValidationFailureReason {
        case dataFileNil
        case dataFileReadFailed(at: URL)
        case missingContentType(acceptableContentTypes: [String])
        . . .
    }

    public enum ResponseSerializationFailureReason {
        case inputDataNil
        case inputDataNilOrZeroLength
        case inputFileNil
        . . .
    }

    case invalidURL(url: URLConvertible)
    case parameterEncodingFailed(reason: ParameterEncodingFailureReason)
    case multipartEncodingFailed(reason: MultipartEncodingFailureReason)
    case responseValidationFailed(reason: ResponseValidationFailureReason)
    case responseSerializationFailed(reason: ResponseSerializationFailureReason)
}

각각Error은 각각 하나의 오류 유형에 대응하고 관련되어 있다case.오류의 원인을 다시 분류하기 위해 4개Reason의 매거를 삽입합니다.코드가 논리적이라고 할 수 밖에 없고 예쁘게 썼다.

오류 설명

extension AFError.ParameterEncodingFailureReason {
    var localizedDescription: String {
        switch self {
        case .missingURL:
            return "URL request to encode was missing a URL"
        case .jsonEncodingFailed(let error):
            return "JSON could not be encoded because of error:
\(error.localizedDescription)" case .propertyListEncodingFailed(let error): return "PropertyList could not be encoded because of error:
\(error.localizedDescription)" } } } extension AFError.MultipartEncodingFailureReason { var localizedDescription: String { switch self { case .bodyPartURLInvalid(let url): return "The URL provided is not a file URL: \(url)" case .bodyPartFilenameInvalid(let url): return "The URL provided does not have a valid filename: \(url)" case .bodyPartFileNotReachable(let url): return "The URL provided is not reachable: \(url)" . . . } } } extension AFError.ResponseSerializationFailureReason { var localizedDescription: String { switch self { case .inputDataNil: return "Response could not be serialized, input data was nil." case .inputDataNilOrZeroLength: return "Response could not be serialized, input data was nil or zero length." case .inputFileNil: return "Response could not be serialized, input file was nil." . . . } } } extension AFError.ResponseValidationFailureReason { var localizedDescription: String { switch self { case .dataFileNil: return "Response could not be validated, data file was nil." case .dataFileReadFailed(let url): return "Response could not be validated, data file could not be read: \(url)." case .missingContentType(let types): return ( "Response Content-Type was missing and acceptable content types " + "(\(types.joined(separator: ","))) do not match \"*/*\"." ) . . . } } }
Reason 속성을 사용하여 각각localizedDescription의 지점에 대해 상세하게 설명합니다.
물론 Reason 이런 내용만 있는 것이 아니라 우리가 사용하기 편리한 확장 등이 많다. 왜냐하면 이것은 나의 이 글의 주요 토론 방향이 아니기 때문에 더 많은 소개를 하지 않는다.관심 있는 사람은 아래의 참고 링크를 보십시오.http://www.jianshu.com/p/99e6ba32f244

좋은 웹페이지 즐겨찾기