import CasePaths
extension CasePathable where AllCasePaths: CasePathReflectable<Self> {
func associatedValue<T: CasePathable>() -> T? where T.AllCasePaths: CasePathReflectable<T> {
let caseKeyPath = Self.allCasePaths[self]
return self[case: caseKeyPath] as? T
}
}
注意:严格来说,我在这里使用的PointFree 的 swift-case-paths库不需要熟悉。从根本上讲,我的问题仅与 Swift 本身有关。
因此,给定上述正确的函数,目标是递归应用它,以检索最深的嵌套值。
但是如何处理这里的类型?因为每个关联值可能是不同的类型。问题是该associatedValue()
函数返回一个T
必须指定的泛型。但对于通用解决方案,我们无法T
提前知道每一个。
我将给出一些具体的例子来提供更多背景信息:
@CasePathable
enum A {
case a(B)
case smthA
}
@CasePathable
enum B {
case b(C)
case smthB
}
@CasePathable
enum C {
case c
case smthC
}
let aValue: A = .a(.b(.c))
let bAssValue: B = aValue.associatedValue()! // .b(.c))
let cAssValue: C = bAssValue.associatedValue()! // .c