swift - 如何获得返回的特定结构类型?
问题描述
我想通过以下特定逻辑接收“结构类型”(?)来初始化结构。
当我将结构的返回值抽象为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
}
}
}
解决方案
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
,它基于相同的协议构造保存/包装我们的类型。这与您所做的相同,可能更容易阅读/理解。
推荐阅读
- python - 在字符串中查找 'xyz' 但不是 '.xyz'
- mysql - 将此 mysql 查询转换为 Laravel Eloquent
- ios - “线程 1:致命错误:在展开可选值时意外发现 nil”通过委托协议传递信息
- pandas - 如何从熊猫数据框中可视化单列
- python - 如何通过周期指数调出日值
- azure - 如何在 Powershell Core 中连接-AzAccount(无提示)?
- python - 使用 urllib 打开带重音符号的 url
- javascript - Javascript - 将事件侦听器添加到多个元素
- c# - 是否可以让任何数据流块类型作为单个输入的结果发送多个中间结果?
- node.js - 保护 AWS S3 下载链接