我想通过以下特定逻辑接收“结构类型”(?)来初始化结构。
当我将结构体的返回值抽象为 MyProtocol
时,有一个 init()
声明,这看起来有点尴尬。
我不确定我能不能做到。
我想返回一个未确定的结构体类型,我该怎么办?
这是最好的吗?
请注意,Opaque Type
不可用,因为它需要支持 iOS 13 或更早版本。
protocol MyProtocol {
init() // Is this for the best?
}
struct AAA: MyProtocol {
var numberAAA: Int // Sample variable.
init() {
print("init AAA")
numberAAA = 100
}
}
struct BBB: MyProtocol {
var numberBBB: Int // Sample variable.
init() {
print("init BBB")
numberBBB = 200
}
}
class MyClass {
func mainLogic() {
let myStruct = randomStruct()
myStruct.init() // This is the reason init () declared in the MyProtocol.
}
func randomStruct() -> MyProtocol.Type {
if Bool.random() {
return AAA.self
} else {
return BBB.self
}
}
}
答案 0 :(得分:0)
init()
作为协议要求似乎很奇怪。没有人阻止您这样做,编译器应该允许这样做,但是我会考虑根据其他一些要求而不仅仅是 init()
来制定协议。
尝试这样做 -
protocol NumberOperation {
var number: Int { get set }
mutating func perform()
}
struct Incrementer: NumberOperation {
var number: Int
mutating func perform() {
number += 1
}
}
struct Decrementer: NumberOperation {
var number: Int
mutating func perform() {
number -= 1
}
}
struct Record<O: NumberOperation> {
public var operation: O
mutating func perform() {
operation.perform()
}
}
class MyClass {
func mainLogic() {
var record = getRecord(type: Incrementer.self)
record.perform()
}
func getRecord<O: NumberOperation>(type: O.Type) -> Record<O> {
if type == Incrementer.self {
return Record(operation: Incrementer(number: 1) as! O)
}
return Record(operation: Decrementer(number: 10) as! O)
}
}
这引入了一个容器类型 Record
,它根据相同的协议构造保存/包装我们的类型。这与您所做的相同,可能更易于阅读/理解。