如何检查"数据类型"是否等于"通用数据类型",并在为True时分配给"



上下文

我有一个包含Generic Typecomponent PropertyGeneric Swift Class。其他几个具有不同Data TypesVariables通过Initializer,然而,它们都符合Generic Protocol

然而,我在Line 11中得到以下Compiler Error

"组件A"不能转换为"C">


代码

protocol Component { ... }
struct ComponentA: Component { ... }
struct ComponentB: Component { ... }
class Main<C: Component> {
var component: C
init(componentA: ComponentA, componentB: ComponentB) {
// I am trying to check, whether componentA equals the Generic Data Type and assign it to the component Property if true.
if case let safeComponent = componentA as C {
self.component = safeComponent
}
}
}

问题

如何实现检查Data Type是否等于Generic Data Type并将其分配给component Property(如果为true(的目标?

您需要检查componentA与C的兼容性。例如:

protocol Component {
var name: String {get}

}
struct ComponentNil: Component {
var name: String
}
struct ComponentA: Component {
var name: String
var a: Int
}
struct ComponentB: Component {
var name: String
var b: Int
}
class Main<C: Component> {
var component: C

init(componentA: ComponentA, componentB: ComponentB) {
// Check that componentA is compatible with type C
if let safeComponent = componentA as? C {
self.component = safeComponent
} else {
// force componentB to be of type C
self.component = componentB as! C
// not that this may throw an error
}
}
}

您至少有3种可能的方法。所有这些都处理了componentA不能被投射到C 的可能性

protocol Component {  }
struct ComponentA: Component {  }
struct ComponentB: Component {  }
// optional `component`
class Main1<C: Component> {
var component: C?
init?(componentA: ComponentA, componentB: ComponentB) {
if let safeComponent = componentA as? C {
self.component = safeComponent
}
}
}
// init throws when precondtions not met
class Main2<C: Component> {
enum Errors: Error {
case preconditionsNotSatisfied
}
var component: C
init(componentA: ComponentA, componentB: ComponentB) throws {
if let safeComponent = componentA as? C {
self.component = safeComponent
} else {
throw Errors.preconditionsNotSatisfied
}
}
}

// init can return nil
class Main3<C: Component> {
var component: C
init?(componentA: ComponentA, componentB: ComponentB) {
if let safeComponent = componentA as? C {
self.component = safeComponent
} else {
return nil
}
}
}

最新更新