Skip to content

Instantly share code, notes, and snippets.

@AFutureD
Created July 27, 2023 03:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AFutureD/c05f4ce0f82d0ef5051d7eab521d845f to your computer and use it in GitHub Desktop.
Save AFutureD/c05f4ce0f82d0ef5051d7eab521d845f to your computer and use it in GitHub Desktop.
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