Swift自定义类型enum类
用Swift 自定义enum类型做的错误码
一般我们通过整数或者字符串来做enum类型的值,这里我们用了一个EageyeErrorCode的结构体来做enum的值,在playground上搞定以下几个要点才可以运行,也花费了不少时间,swift的enum类型真是博大精深。
1、StringLiteralConvertible 字面量转换
将字符串转换为EageyeErrorCode 结构
2、Equatable可等性协议
==方法,似乎必须实现Equatable才可以使用自己定义的struct做enum的元素
3、enum的构建方法
自己写了一个valueOfId的静态方法,来讲error码定位到错误枚举类型
4、代码如下:
structEageyeErrorCode:Equatable{
varcode:String=""
vartitle:String=""
vardescribe:String=""
varhttpRspCode:Int=0
init() {
self.code=""
self.title=""
self.describe=""
self.httpRspCode=0
}
init(code:String, title:String, desc:String, httpRspCode:Int) {
self.code= code
self.title= title
self.describe= desc
self.httpRspCode= httpRspCode
}
}
func== (lhs:EageyeErrorCode, rhs:EageyeErrorCode) ->Bool{
returntrue
}
//extension EageyeErrorCode: ArrayLiteralConvertible {
//
//init(arrayLiteral elements: String...) {
//self.code = elements[0]
//self.title = elements[1]
//self.describe = elements[2]
//self.httpRspCode = Int(elements[3])!
//}
//}
extensionEageyeErrorCode:StringLiteralConvertible{
init(stringLiteral value:String) {
leterror =errorCodeFromString(value)
self.code= error[0]
self.title= error[1]
self.describe= error[2]
self.httpRspCode=Int(error[3])!
}
init(extendedGraphemeClusterLiteral value:String) {
leterror =errorCodeFromString(value)
self.code= error[0]
self.title= error[1]
self.describe= error[2]
self.httpRspCode=Int(error[3])! }
init(unicodeScalarLiteral value:String) {
leterror =errorCodeFromString(value)
self.code= error[0]
self.title= error[1]
self.describe= error[2]
self.httpRspCode=Int(error[3])!
}
funcerrorCodeFromString(str:String) -> [String] {
letstring:NSString= str
letsubstringArry = string.componentsSeparatedByString(",")
returnsubstringArry
}
}
enumErrorCodeType:EageyeErrorCode{
// case ERROR_00100 = ["00100", "公共基础异常", "公共基础异常", "500"]
caseERROR_00100 ="00100,公共基础异常,公共基础异常,500"
caseERROR_00101 ="00101,公共基础异常,空指针异常,500"
staticfuncvalueOfId(id:String) ->ErrorCodeType{
switchid {
case"00100":
returnERROR_00100
case"00101":
returnERROR_00101
default:
returnERROR_00100
}
}
}
ErrorCodeType.ERROR_00100.rawValue.code
ErrorCodeType.ERROR_00100.rawValue.describe
ErrorCodeType.ERROR_00100.rawValue.httpRspCode
ErrorCodeType.valueOfId("00100")