0

这是现实生活中的代码。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'.

4

2 回答 2

0

无论如何,我认为这应该是您的条件下的第三种情况。

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, let genericInt = 0 as? T {
        return TestClass(value: genericInt)
    } else if let genericString = "" as? T {
        return TestClass(value: genericString)
    }

    return nil
}
于 2020-06-17T07:42:24.600 回答
0

Int、String 和 T 符合 TestProtocol。但是三个都不一样。

根据您的代码,您应该将 T.type 放入TestCalss(value: T)not TestProtocol

所以你应该cast争论

import Foundation

protocol TestProtocol { }
extension Int: TestProtocol { }
extension String: TestProtocol { }

class TestClass<T: TestProtocol> {
    let value: T
    init(value: T) {
        self.value = value
    }

    static func makeTestClass(isInt: Bool) -> TestClass? {
        switch isInt {
        case true where 0 is T:
            return TestClass(value: 0 as! T)
        case false where "" is T:
            return TestClass(value: "" as! T)
        default:
            return nil
        }
    }
}
于 2020-06-17T07:53:32.583 回答