这是现实生活中的代码。https://gist.github.com/Terriermon/0fa20dae02fed0c39b4bfe54e7db50b8 这是新代码。我认为这段代码显示了我项目中的问题。
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
}
}
这是代码。而且我不想使用as!,因为它在某些情况下无法工作。在我的项目中,如果我使用 as,它会抱怨Cast from 'AnyValidatorConvertible<Int>' to unrelated type 'AnyValidatorConvertible<T>' always fails
protocol TestProtocol { }
extension Int: TestProtocol { }
extension String: TestProtocol { }
class TestClass<T: TestProtocol> {
let value: T
init(value: T) {
self.value = value
}
}
func testFunction<T: TestProtocol>(isInt: Bool) -> TestClass<T> {
if isInt {
return TestClass(value: 0)
} else {
return TestClass(value: "")
}
}
这是错误信息。Cannot convert value of type 'Int' to expected argument type 'T'.