0

Here is my code

func testFuncA<T>(_ value: T) {
    if let rValue = value as? Encodable {
        testFuncB(rValue)//error in here: Cannot invoke 'testFuncB' with an argument list of type '(Encodable)'
    }
}

func testFuncB<T: Encodable>(_ value: T)  {

}

why can not invoketestFuncB? is T can cast to T: Encodable ?

jan.yave
  • 33
  • 4
  • Protocols don't conform to themselves; `Encodable` is not a type that conforms to `Encodable`, therefore you cannot use it to satisfy the type variable `T` where `T : Encodable`. – Hamish Sep 14 '17 at 07:44
  • Is there no way to invoke `testFuncB` with `value`? – jan.yave Sep 14 '17 at 07:55
  • You could use a type-erasing `AnyEncodable` wrapper (such as shown in the linked Q&A) which you could then pass to `testFuncB`, although you wouldn't be able to do the same for decoding (you need a concrete type to decode into). – Hamish Sep 14 '17 at 08:52
  • Your comment is very usefull, but if `testFuncB` is an Apple API such as `JSONEncoder`'s `func encode(_ value: T) throws -> Data where T : Encodable`, it's also can not invoke – jan.yave Sep 14 '17 at 09:04
  • Not sure I follow you; [works fine for me](https://gist.github.com/hamishknight/581647517cca4e2d2991db81247f7fa5). – Hamish Sep 14 '17 at 09:06
  • Oh,I go the wrong way, lost to comform`Encodable`,Thank you very much! – jan.yave Sep 14 '17 at 09:24

0 Answers0