Swift 枚举符合单一协议的关联值
Swift Enum associated values conforming to single protocol
如何在不使用详尽开关的情况下将当前枚举案例的关联值作为 Refreshable 获取?
在这种情况下,我只需要将其作为协议检索,用于每个案例关联类型。
class Type1: Refreshable {}
class Type2: Refreshable {}
class Type3: Refreshable {}
protocol Refreshable {
func refresh()
}
enum ContentType {
case content1(Type1 & Refreshable)
case content2(Type2 & Refreshable)
case content3(Type3 & Refreshable)
func refreshMe() {
//self.anyValue.refresh() //Want simple solution to get to the refresh() method not knowing actual current state
}
}
我已经找到了解决方案,以防有人也需要它。
enum ContentType {
case content1(Type1 & Refreshable)
case content2(Type2 & Refreshable)
case content3(someLabel: Type3 & Refreshable)
func refreshMe() {
let caseReflection = Mirror(reflecting: self).children.first!.value
(caseReflection as? Refreshable)?.refresh() //If associated type doesn't have label
let refreshable = Mirror(reflecting: caseReflection).children.first?.value as? Refreshable
refreshable?.refresh() //If associated type has label
}
}
如何在不使用详尽开关的情况下将当前枚举案例的关联值作为 Refreshable 获取? 在这种情况下,我只需要将其作为协议检索,用于每个案例关联类型。
class Type1: Refreshable {}
class Type2: Refreshable {}
class Type3: Refreshable {}
protocol Refreshable {
func refresh()
}
enum ContentType {
case content1(Type1 & Refreshable)
case content2(Type2 & Refreshable)
case content3(Type3 & Refreshable)
func refreshMe() {
//self.anyValue.refresh() //Want simple solution to get to the refresh() method not knowing actual current state
}
}
我已经找到了解决方案,以防有人也需要它。
enum ContentType {
case content1(Type1 & Refreshable)
case content2(Type2 & Refreshable)
case content3(someLabel: Type3 & Refreshable)
func refreshMe() {
let caseReflection = Mirror(reflecting: self).children.first!.value
(caseReflection as? Refreshable)?.refresh() //If associated type doesn't have label
let refreshable = Mirror(reflecting: caseReflection).children.first?.value as? Refreshable
refreshable?.refresh() //If associated type has label
}
}