用Swift 自定義enum類型做的錯誤碼
? ? ? ?一般我們通過整數(shù)或者字符串來做enum類型的值,這里我們用了一個EageyeErrorCode的結(jié)構(gòu)體來做enum的值洗显,在playground上搞定以下幾個要點才可以運行,也花費了不少時間阵幸,swift的enum類型真是博大精深臊诊。
1、StringLiteralConvertible 字面量轉(zhuǎn)換
將字符串轉(zhuǎn)換為EageyeErrorCode 結(jié)構(gòu)
2状原、Equatable可等性協(xié)議
==方法聋呢,似乎必須實現(xiàn)Equatable才可以使用自己定義的struct做enum的元素
3、enum的構(gòu)建方法
自己寫了一個valueOfId的靜態(tài)方法颠区,來講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", "公共基礎(chǔ)異常", "公共基礎(chǔ)異常", "500"]
caseERROR_00100 ="00100,公共基礎(chǔ)異常,公共基礎(chǔ)異常,500"
caseERROR_00101 ="00101,公共基礎(chǔ)異常,空指針異常,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")