Skip to content

Commit

Permalink
Open existentials sent to PartialCaseKeyPath.callAsFunction (#145)
Browse files Browse the repository at this point in the history
  • Loading branch information
stephencelis authored Jan 30, 2024
1 parent 76d7791 commit 8cc3bc0
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 3 deletions.
9 changes: 6 additions & 3 deletions Sources/CasePaths/CasePathable.swift
Original file line number Diff line number Diff line change
Expand Up @@ -279,11 +279,14 @@ extension PartialCaseKeyPath {
/// type, the operation will fail.
/// - Returns: An enum for the case of this key path that holds the given value, or `nil`.
@_disfavoredOverload
public func callAsFunction<Enum: CasePathable, AnyAssociatedValue>(
_ value: AnyAssociatedValue
public func callAsFunction<Enum: CasePathable>(
_ value: Any
) -> Enum?
where Root == Case<Enum> {
(Case<Enum>()[keyPath: self] as? Case<AnyAssociatedValue>)?.embed(value) as? Enum
func open<AnyAssociatedValue>(_ value: AnyAssociatedValue) -> Enum? {
(Case<Enum>()[keyPath: self] as? Case<AnyAssociatedValue>)?.embed(value) as? Enum
}
return _openExistential(value, do: open)
}
}

Expand Down
20 changes: 20 additions & 0 deletions Tests/CasePathsTests/CasePathsTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -164,10 +164,30 @@ final class CasePathsTests: XCTestCase {
XCTAssertEqual(.int(42), Foo.bar(.int(42))[case: partialPath] as? Bar)
XCTAssertNil(Foo.baz(.string("Hello"))[case: partialPath])
}

func testExistentials() {
let caseA: PartialCaseKeyPath<A> = \.a
let caseB: PartialCaseKeyPath<B> = \.b

let a = A.a("Hello")
guard let valueA = a[case: caseA] else { return XCTFail() }
guard let b = caseB(valueA) else { return XCTFail() }
XCTAssertEqual(b, .b("Hello"))
}
#endif
}

#if swift(>=5.9)
@CasePathable
enum A: Equatable {
case a(String)
}

@CasePathable
enum B: Equatable {
case b(String)
}

@CasePathable @dynamicMemberLookup enum Foo: Equatable {
case bar(Bar)
case baz(Baz)
Expand Down

0 comments on commit 8cc3bc0

Please sign in to comment.