protocol TestReturnTypeProtocol {
associatedtype T
func test(_ type: T)
}
protocol Testable {}
extension Int: Testable { }
extension String: Testable { }
class AnyTestReturnType<Type>: TestReturnTypeProtocol where Type: Testable {
init<P: TestReturnTypeProtocol>(_ p: P) where P.T == Type { }
func test(_ type: Type) { }
}
class IntReturnClass: TestReturnTypeProtocol {
func test(_ type: Int) { }
}
class StringReturnClass: TestReturnTypeProtocol {
func test(_ type: String) { }
}
func tesfFunction<T: Testable>(isInt: Bool) -> AnyTestReturnType<T> {
if isInt {
let intRet = AnyTestReturnType(IntReturnClass())
return intRet
} else {
let strRet = AnyTestReturnType<String>(StringReturnClass())
return strRet
}
}
I can use the as! T
to solve this question, It will complain Cast from 'AnyTestReturnType <Int>' to unrelated type 'AnyTestReturnType <T>' always fails