Created
July 27, 2023 03:10
-
-
Save AFutureD/c05f4ce0f82d0ef5051d7eab521d845f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
import XCTest | |
public protocol A { | |
var value: Int { get } | |
} | |
public protocol B { | |
associatedtype T: A | |
func check<T>(input: T) -> Int | |
} | |
struct Impl<U>: B where U: A { | |
typealias T = U | |
let path: KeyPath<U, Int> | |
func check<T>(input: T) -> Int { | |
return (input as! U)[keyPath: path] | |
} | |
} | |
final class GenericTests: XCTestCase { | |
func testOne() { | |
struct One: A { | |
var value: Int | |
} | |
struct Two: A { | |
var value: Int | |
} | |
let impl = Impl(path: \One.value) | |
let one = One(value: 1) | |
let two = Two(value: 2) | |
let _ = impl.check(input: one) // 1 | |
let _ = impl.check(input: two) // error | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment