enum Movement { case Left case Right case Top case Bottom } let aMovement = Movement.Left switch aMovement { case .Left: print("left") default: print("Unknow") } if case .Left = aMovement { print("Left") } if .Left == aMovement { print("Left") }
enum Season: Int { case Spring = 0 case Summer = 1 case Autumn = 2 case Winter = 3 }
enum House: String { case ZhangSan = "I am zhangsan" case LiSi = "I am lisi" } let zs = House.ZhangSan print(zs.rawValue) enum CompassPoint: String { case North, South, East, West } let n = CompassPoint.North print(n.rawValue) let s = CompassPoint(rawValue: "South");
enum Constants: Double { case π = 3.14159 case e = 2.71828 case φ = 1.61803398874 case λ = 1.30357 } let pai = Constants.π print(pai.rawValue)
enum VNodeFlags : UInt32 { case Delete = 0x00000001 case Write = 0x00000002 case Extended = 0x00000004 case Attrib = 0x00000008 case Link = 0x00000010 case Rename = 0x00000020 case Revoke = 0x00000040 case None = 0x00000080 }
enum Character { enum Weapon { case Bow case Sword case Lance case Dagger } enum Helmet { case Wooden case Iron case Diamond } case Thief case Warrior case Knight } let character = Character.Thief let weapon = Character.Weapon.Bow let helmet = Character.Helmet.Iron
struct Scharacter { enum CharacterType { case Thief case Warrior case Knight } enum Weapon { case Bow case Sword case Lance case Dagger } let type: CharacterType let weapon: Weapon } let sc = Scharacter(type: .Thief, weapon: .Bow) print(sc.type)
enum Trade { case Buy(stock: String, amount: Int) case Sell(stock: String, amount: Int) } let trade = Trade.Buy(stock: "Car", amount: 100) if case let Trade.Buy(stock, amount) = trade { print("buy \(amount) of \(stock)") } enum Trade0 { case Buy(String, Int) case Sell(String, Int) } let trade0 = Trade0.Buy("Car0", 100) if case let Trade0.Buy(stock, amount) = trade0 { print("buy \(amount) of \(stock)") }
enum Wearable { enum Weight: Int { case Light = 2 } enum Armor: Int { case Light = 2 } case Helmet(weight: Weight, armor: Armor) func attributes() -> (weight: Int, armor: Int) { switch self { case .Helmet(let w, let a): return (weight: w.rawValue * 2, armor: a.rawValue * 4) } } } let test = Wearable.Helmet(weight: .Light, armor: .Light).attributes() print(test) enum Device { case iPad, iPhone, AppleTV, AppleWatch func introduced() -> String { switch self { case .AppleTV: return "\(self) was introduced 2006" case .iPhone: return "\(self) was introduced 2007" case .iPad: return "\(self) was introduced 2010" case .AppleWatch: return "\(self) was introduced 2014" } } } print (Device.iPhone.introduced())
enum Device1 { case iPad, iPhone var year: Int { switch self { case .iPad: return 2010 case .iPhone: return 2007 } } } let iPhone = Device1.iPhone print(iPhone.year)
经过ParameterEncodingFailureReason
咱们可以很清楚的看出来这是一个参数编码的错误缘由。你们注意reason
这个词,在命名中,有或者没有这个词,表达的意境彻底不一样,所以,Alamofire牛逼就体如今这些细节之中。json
public enum AFError: Error { /// The underlying reason the parameter encoding error occurred. /// /// - missingURL: The URL request did not have a URL to encode. /// - jsonEncodingFailed: JSON serialization failed with an underlying system error during the /// encoding process. /// - propertyListEncodingFailed: Property list serialization failed with an underlying system error during /// encoding process. public enum ParameterEncodingFailureReason { case missingURL case jsonEncodingFailed(error: Error) case propertyListEncodingFailed(error: Error) } }
ParameterEncodingFailureReason
自己是一个enum,同时,它又被包含在AFError
之中,这说明枚举之中能够有另外一个枚举。那么像这种状况咱们怎么使用呢?看下边的代码:swift
let parameterErrorReason = AFError.ParameterEncodingFailureReason.missingURL
枚举的访问是一级一级进行的。咱们再看这行代码:case jsonEncodingFailed(error: Error)
。jsonEncodingFailed(error: Error)
并非函数,就是枚举的一个普通的子选项。(error: Error)
是它的一个关联值,相对于任何一个子选项,咱们均可以关联任何值,它的意义就在于,把这些值与子选项进行绑定,方便在须要的时候调用。咱们会在下边讲解如何获取关联值。服务器
参数编码有一下几种方式:网络
Alamofire中是如何进行参数编码的,这方面的内容会在后续的ParameterEncoding.swift
这一篇文章中给出详细的解释。那么编码失败的缘由可能为:框架
missingURL
给定的urlRequest.url为nil的状况抛出错误jsonEncodingFailed(error: Error)
当选择把参数编码成JSON格式的状况下,参数JSON化抛出的错误propertyListEncodingFailed(error: Error)
这个同上综上所述,ParameterEncodingFailureReason
封装了参数编码的错误,可能出现的错误类型为Error,说明这些所谓通常是调用系统Api产生的错误。ide
public enum MultipartEncodingFailureReason { case bodyPartURLInvalid(url: URL) case bodyPartFilenameInvalid(in: URL) case bodyPartFileNotReachable(at: URL) case bodyPartFileNotReachableWithError(atURL: URL, error: Error) case bodyPartFileIsDirectory(at: URL) case bodyPartFileSizeNotAvailable(at: URL) case bodyPartFileSizeQueryFailedWithError(forURL: URL, error: Error) case bodyPartInputStreamCreationFailed(for: URL) case outputStreamCreationFailed(for: URL) case outputStreamFileAlreadyExists(at: URL) case outputStreamURLInvalid(url: URL) case outputStreamWriteFailed(error: Error) case inputStreamReadFailed(error: Error) }
多部分编码错误通常发生在上传或下载请求中对数据的处理过程当中,这里边最重要的是对上传数据的处理过程,会在后续的MultipartFormData.swift
这一篇文章中给出详细的解释,咱们就简单的分析下MultipartEncodingFailureReason
子选项错误出现的缘由:函数
bodyPartURLInvalid(url: URL)
上传数据时,能够经过fileURL的方式,读取本地文件数据,若是fileURL不可用,就会抛出这个错误bodyPartFilenameInvalid(in: URL)
若是使用fileURL的lastPathComponent
或者pathExtension
获取filename为空抛出的错误bodyPartFileNotReachable(at: URL)
经过fileURL不能访问数据,也就是不可达的bodyPartFileNotReachableWithError(atURL: URL, error: Error)
这个不一样于bodyPartFileNotReachable(at: URL)
,当尝试检测fileURL是否是可达的状况下抛出的错误bodyPartFileIsDirectory(at: URL)
当fileURL是一个文件夹时抛出错误bodyPartFileSizeNotAvailable(at: URL)
当使用系统Api获取fileURL指定文件的size出现错误bodyPartFileSizeQueryFailedWithError(forURL: URL, error: Error)
查询fileURL指定文件size出现错误bodyPartInputStreamCreationFailed(for: URL)
经过fileURL建立inputStream出现错误outputStreamCreationFailed(for: URL)
当尝试把编码后的数据写入到硬盘时,建立outputStream出现错误outputStreamFileAlreadyExists(at: URL)
数据不能被写入,由于指定的fileURL已经存在outputStreamURLInvalid(url: URL)
fileURL不是一个file URLoutputStreamWriteFailed(error: Error)
数据流写入错误inputStreamReadFailed(error: Error)
数据流读入错误综上所述,这些错误基本上都跟数据的操做相关,这个在后续会作出很详细的说明。fetch
public enum ResponseValidationFailureReason { case dataFileNil case dataFileReadFailed(at: URL) case missingContentType(acceptableContentTypes: [String]) case unacceptableContentType(acceptableContentTypes: [String], responseContentType: String) case unacceptableStatusCode(code: Int) }
Alamofire无论请求是否成功,都会返回response。它提供了验证ContentType和StatusCode的功能,关于验证,再后续的文章中会有详细的解答,咱们先看看这些缘由:编码
dataFileNil
保存数据的URL不存在,这种状况通常出如今下载任务中,指的是下载代理中的fileURL缺失dataFileReadFailed(at: URL)
保存数据的URL没法读取数据,同上missingContentType(acceptableContentTypes: [String])
服务器返回的response不包含ContentType且提供的acceptableContentTypes不包含通配符(通配符表示能够接受任何类型)unacceptableContentType(acceptableContentTypes: [String], responseContentType: String)
ContentTypes不匹配unacceptableStatusCode(code: Int)
StatusCode不匹配public enum ResponseSerializationFailureReason { case inputDataNil case inputDataNilOrZeroLength case inputFileNil case inputFileReadFailed(at: URL) case stringSerializationFailed(encoding: String.Encoding) case jsonSerializationFailed(error: Error) case propertyListSerializationFailed(error: Error) }
咱们在Alamofire源码解读系列(一)之概述和使用中已经提到,Alamofire支持把服务器的response序列成几种数据格式。url
那么在序列化的过程当中,极可能会发生下边的错误:
inputDataNil
服务器返回的response没有数据inputDataNilOrZeroLength
服务器返回的response没有数据或者数据的长度是0inputFileNil
指向数据的URL不存在inputFileReadFailed(at: URL)
指向数据的URL没法读取数据stringSerializationFailed(encoding: String.Encoding)
当使用指定的String.Encoding序列化数据为字符串时,抛出的错误jsonSerializationFailed(error: Error)
JSON序列化错误propertyListSerializationFailed(error: Error)
plist序列化错误上边内容中介绍的ParameterEncodingFailureReason
MultipartEncodingFailureReason
ResponseValidationFailureReason
和 ResponseSerializationFailureReason
,他们是定义在AFError
中独立的枚举,他们之间是包含和被包含的关系,理解这一点很重要,由于有了这种包含的管理,在使用中就须要经过AFError.ParameterEncodingFailureReason
这种方式进行操做。
那么最重要的问题就是,如何把上边4个独立的枚举进行串联呢?Alamofire巧妙的地方就在这里,有4个独立的枚举,分别表明4大错误。也就是说这个网络框架确定有这4大错误模块,咱们只须要给AFError设计4个子选项,每一个子选项关联上上边4个独立枚举的值就ok了。
这个设计真的很巧妙,试想,若是把全部的错误都放到AFError中,就显得很是冗余。那么下边的代码就呼之欲出了,你们好好体会体会在swift下这么设计的妙用:
case invalidURL(url: URLConvertible) case parameterEncodingFailed(reason: ParameterEncodingFailureReason) case multipartEncodingFailed(reason: MultipartEncodingFailureReason) case responseValidationFailed(reason: ResponseValidationFailureReason) case responseSerializationFailed(reason: ResponseSerializationFailureReason)
也许在开发中,咱们完成了上边的代码就认为够用了,但对于一个开源框架而言,远远是不够的。咱们一点点进行剖析:
如今给定一条数据:
func findErrorType(error: AFError) { }
我只须要知道这个error是否是参数编码错误,应该怎么办?所以为AFError提供5个布尔类型的属性,专门用来获取当前的错误是否是某个指定的类型。这个功能的实现比较简单,代码以下:
extension AFError { /// Returns whether the AFError is an invalid URL error. public var isInvalidURLError: Bool { if case .invalidURL = self { return true } return false } /// Returns whether the AFError is a parameter encoding error. When `true`, the `underlyingError` property will /// contain the associated value. public var isParameterEncodingError: Bool { if case .parameterEncodingFailed = self { return true } return false } /// Returns whether the AFError is a multipart encoding error. When `true`, the `url` and `underlyingError` properties /// will contain the associated values. public var isMultipartEncodingError: Bool { if case .multipartEncodingFailed = self { return true } return false } /// Returns whether the `AFError` is a response validation error. When `true`, the `acceptableContentTypes`, /// `responseContentType`, and `responseCode` properties will contain the associated values. public var isResponseValidationError: Bool { if case .responseValidationFailed = self { return true } return false } /// Returns whether the `AFError` is a response serialization error. When `true`, the `failedStringEncoding` and /// `underlyingError` properties will contain the associated values. public var isResponseSerializationError: Bool { if case .responseSerializationFailed = self { return true } return false } }
总而言之,这些都是给AFError这个枚举扩展的属性,还包含下边这些属性:
urlConvertible: URLConvertible?
获取某个属性,这个属性实现了URLConvertible协议,在AFError中只有case invalidURL(url: URLConvertible)这个选项符合要求
/// The `URLConvertible` associated with the error. public var urlConvertible: URLConvertible? { switch self { case .invalidURL(let url): return url default: return nil } }
url: URL?
获取AFError中的URL,固然这个URL只跟MultipartEncodingFailureReason这个子选项有关
/// The `URL` associated with the error. public var url: URL? { switch self { case .multipartEncodingFailed(let reason): return reason.url default: return nil } }
underlyingError: Error?
AFError中封装的全部的可能出现的错误中,并非每种可能都会返回Error这个错误信息,所以这个属性是可选的
/// The `Error` returned by a system framework associated with a `.parameterEncodingFailed`, /// `.multipartEncodingFailed` or `.responseSerializationFailed` error. public var underlyingError: Error? { switch self { case .parameterEncodingFailed(let reason): return reason.underlyingError case .multipartEncodingFailed(let reason): return reason.underlyingError case .responseSerializationFailed(let reason): return reason.underlyingError default: return nil } }
acceptableContentTypes: [String]?
可接受的ContentType
/// The response `Content-Type` of a `.responseValidationFailed` error. public var responseContentType: String? { switch self { case .responseValidationFailed(let reason): return reason.responseContentType default: return nil } }
responseCode: Int?
响应码
/// The response code of a `.responseValidationFailed` error. public var responseCode: Int? { switch self { case .responseValidationFailed(let reason): return reason.responseCode default: return nil } }
failedStringEncoding: String.Encoding?
错误的字符串编码
/// The `String.Encoding` associated with a failed `.stringResponse()` call. public var failedStringEncoding: String.Encoding? { switch self { case .responseSerializationFailed(let reason): return reason.failedStringEncoding default: return nil } }
这里是一个小的分割线,在上边属性的获取中,也是用到了下边代码中的扩展功能:
extension AFError.ParameterEncodingFailureReason { var underlyingError: Error? { switch self { case .jsonEncodingFailed(let error), .propertyListEncodingFailed(let error): return error default: return nil } } } extension AFError.MultipartEncodingFailureReason { var url: URL? { switch self { case .bodyPartURLInvalid(let url), .bodyPartFilenameInvalid(let url), .bodyPartFileNotReachable(let url), .bodyPartFileIsDirectory(let url), .bodyPartFileSizeNotAvailable(let url), .bodyPartInputStreamCreationFailed(let url), .outputStreamCreationFailed(let url), .outputStreamFileAlreadyExists(let url), .outputStreamURLInvalid(let url), .bodyPartFileNotReachableWithError(let url, _), .bodyPartFileSizeQueryFailedWithError(let url, _): return url default: return nil } } var underlyingError: Error? { switch self { case .bodyPartFileNotReachableWithError(_, let error), .bodyPartFileSizeQueryFailedWithError(_, let error), .outputStreamWriteFailed(let error), .inputStreamReadFailed(let error): return error default: return nil } } } extension AFError.ResponseValidationFailureReason { var acceptableContentTypes: [String]? { switch self { case .missingContentType(let types), .unacceptableContentType(let types, _): return types default: return nil } } var responseContentType: String? { switch self { case .unacceptableContentType(_, let responseType): return responseType default: return nil } } var responseCode: Int? { switch self { case .unacceptableStatusCode(let code): return code default: return nil } } } extension AFError.ResponseSerializationFailureReason { var failedStringEncoding: String.Encoding? { switch self { case .stringSerializationFailed(let encoding): return encoding default: return nil } } var underlyingError: Error? { switch self { case .jsonSerializationFailed(let error), .propertyListSerializationFailed(let error): return error default: return nil } } }
在开发中,若是程序遇到错误,咱们每每会给用户展现更加直观的信息,这就要求咱们把错误信息转换成易于理解的内容。所以咱们只要实现LocalizedError协议就行了。这里边的内容很简单,在这里就直接把代码写上了,不作分析:
extension AFError: LocalizedError { public var errorDescription: String? { switch self { case .invalidURL(let url): return "URL is not valid: \(url)" case .parameterEncodingFailed(let reason): return reason.localizedDescription case .multipartEncodingFailed(let reason): return reason.localizedDescription case .responseValidationFailed(let reason): return reason.localizedDescription case .responseSerializationFailed(let reason): return reason.localizedDescription } } } 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:\n\(error.localizedDescription)" case .propertyListEncodingFailed(let error): return "PropertyList could not be encoded because of error:\n\(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)" case .bodyPartFileNotReachableWithError(let url, let error): return ( "The system returned an error while checking the provided URL for " + "reachability.\nURL: \(url)\nError: \(error)" ) case .bodyPartFileIsDirectory(let url): return "The URL provided is a directory: \(url)" case .bodyPartFileSizeNotAvailable(let url): return "Could not fetch the file size from the provided URL: \(url)" case .bodyPartFileSizeQueryFailedWithError(let url, let error): return ( "The system returned an error while attempting to fetch the file size from the " + "provided URL.\nURL: \(url)\nError: \(error)" ) case .bodyPartInputStreamCreationFailed(let url): return "Failed to create an InputStream for the provided URL: \(url)" case .outputStreamCreationFailed(let url): return "Failed to create an OutputStream for URL: \(url)" case .outputStreamFileAlreadyExists(let url): return "A file already exists at the provided URL: \(url)" case .outputStreamURLInvalid(let url): return "The provided OutputStream URL is invalid: \(url)" case .outputStreamWriteFailed(let error): return "OutputStream write failed with error: \(error)" case .inputStreamReadFailed(let error): return "InputStream read failed with error: \(error)" } } } 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." case .inputFileReadFailed(let url): return "Response could not be serialized, input file could not be read: \(url)." case .stringSerializationFailed(let encoding): return "String could not be serialized with encoding: \(encoding)." case .jsonSerializationFailed(let error): return "JSON could not be serialized because of error:\n\(error.localizedDescription)" case .propertyListSerializationFailed(let error): return "PropertyList could not be serialized because of error:\n\(error.localizedDescription)" } } } 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 \"*/*\"." ) case .unacceptableContentType(let acceptableTypes, let responseType): return ( "Response Content-Type \"\(responseType)\" does not match any acceptable types: " + "\(acceptableTypes.joined(separator: ","))." ) case .unacceptableStatusCode(let code): return "Response status code was unacceptable: \(code)." } } }
做者:老马的春天 连接:https://www.jianshu.com/p/99e6ba32f244 來源:简书 著做权归做者全部。商业转载请联系做者得到受权,非商业转载请注明出处。