Sid*_*rth 10 enums ios swift rawrepresentable
我正在尝试创建一个我想初始化的结构的枚举:
struct CustomStruct {
var variable1: String
var variable2: AnyClass
var variable3: Int
init (variable1: String, variable2: AnyClass, variable3: Int) {
self.variable1 = variable1
self.variable2 = variable2
self.variable3 = variable3
}
}
enum AllStructs: CustomStruct {
case getData
case addNewData
func getAPI() -> CustomStruct {
switch self {
case getData:
return CustomStruct(variable1:"data1", variable2: SomeObject.class, variable3: POST)
case addNewData:
// Same to same
default:
return nil
}
}
}
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
Type AllStructs不符合协议'RawRepresentable'
我假设枚举不能以这种方式使用.我们必须使用原语.
Ahm*_*d F 15
它应该是:
struct CustomStruct {
var apiUrl: String
var responseType: AnyObject
var httpType: Int
init (variable1: String, variable2: AnyObject, variable3: Int) {
self.apiUrl = variable1
self.responseType = variable2
self.httpType = variable3
}
}
enum MyEnum {
case getData
case addNewData
func getAPI() -> CustomStruct {
switch self {
case .getData:
return CustomStruct(variable1: "URL_TO_GET_DATA", variable2: 11 as AnyObject, variable3: 101)
case .addNewData:
return CustomStruct(variable1: "URL_TO_ADD_NEW_DATA", variable2: 12 as AnyObject, variable3: 102)
}
}
}
Run Code Online (Sandbox Code Playgroud)
用法:
let data = MyEnum.getData
let myObject = data.getAPI()
// this should logs: "URL_TO_GET_DATA 11 101"
print(myObject.apiUrl, myObject.responseType, myObject.httpType)
Run Code Online (Sandbox Code Playgroud)
请注意,在命名约定时,struct应命名为CustomStruct和枚举命名为MyEnum.
事实上,我不太确定是否需要CustomStruct成为MyEnum实现你想要的东西的父母; 如上面的片段中所述,您可以根据引用的枚举的值返回结构的实例.
Umb*_*ndi 13
我不是在评论在这里使用枚举的选择,而只是解释为什么你得到了这个错误以及如何声明一个自定义对象作为父对象的枚举.
错误显示您的问题,CustomStruct必须实现RawRepresentable用作该枚举的基类.
这是一个简化的示例,向您展示了您需要做的事情:
struct CustomStruct : ExpressibleByIntegerLiteral, Equatable {
var rawValue: Int = 0
init(integerLiteral value: Int){
self.rawValue = value
}
static func == (lhs: CustomStruct, rhs: CustomStruct) -> Bool {
return
lhs.rawValue == rhs.rawValue
}
}
enum AllStructs: CustomStruct {
case ONE = 1
case TWO = 2
}
Run Code Online (Sandbox Code Playgroud)
我们在此代码段中可以看到一些重要的事情:
RawRepresentable包括实现一个Expressible协议(init?(rawValue:)将利用我们编写的支持文字的初始化程序).CustomStruct基类型实现相等运算符.