Swift⾃定义类型enum类enum c++
⽤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.title=""
self.describe=""
self.httpRspCode=0
}
init(code:String, title:String, desc:String, httpRspCode:Int) {
self.title= title
self.describe= desc
self.httpRspCode= httpRspCode
}
}
func== (lhs:EageyeErrorCode, rhs:EageyeErrorCode) ->Bool{ returntrue
}
//extension EageyeErrorCode: ArrayLiteralConvertible {
//
/
/init(arrayLiteral elements: ) {
//de = 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.title= error[1]
self.describe= error[2]
self.httpRspCode=Int(error[3])!
}
init(extendedGraphemeClusterLiteral value:String) {
leterror =errorCodeFromString(value)
self.title= error[1]
self.describe= error[2]
self.httpRspCode=Int(error[3])! }
init(unicodeScalarLiteral value:String) {
leterror =errorCodeFromString(value)
self.title= error[1]
self.describe= error[2]
self.httpRspCode=Int(error[3])!
}
funcerrorCodeFromString(str:String) -> [String] {
letstring:NSString= str
letsubstringArry = stringponentsSeparatedByString(",") 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_de
ErrorCodeType.ERROR_00100.rawValue.describe
ErrorCodeType.ERROR_00100.rawValue.httpRspCode ErrorCodeType.valueOfId("00100")

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。