Swift 표준 라이브러리 해석: 프로토콜 편 - Error
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
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSONJSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다. 그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다. 저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.