0

I have a function that returns the specific Unicode.Unicodec interface, as follows:

static func encodingStrToDecoder(_ encoding: String) -> some UnicodeCodec {
    switch encoding {
    case Encoding.utf8:
        print("Returning UTF8")
        return UTF8()
    case Encoding.utf16:
        print("Returning UTF16")
        return UTF16()
    case Encoding.utf32:
        print("Returning UTF32")
        return UTF32()
    default:
        print("Returning UTF8 (DEFAULT)")
        return UTF8()
    }
}

Encoding.utf8 and such are just String constants.

However, I get a

Function declares an opaque return type, but the return statements in its body do not have matching underlying types

error. What am I doing wrong?

ABCD Man
  • 79
  • 4
  • You are misunderstanding what `some UnicodeCodec` means. It doesn't magically allow you to return different types in a method. You still have to return one type and one type only. Not sometimes `UTF8`, and sometimes `UTF32`... – Sweeper Sep 01 '20 at 02:06
  • @Sweeper But UTF8 AND UTF32 AND UTF16 both conform to UnicodeCodec. – ABCD Man Sep 01 '20 at 02:07
  • But `UnicodeCodec` has associated types, which is the main reason why you can't do this in the first place, with or without `some`. Suppose I do `let codec = encodingStrToDecoder(someUserInput)`, and I want to call `decode` on `codec`. What should type I put as the first argument? How does the compiler know? See [this](https://stackoverflow.com/questions/36348061/protocol-can-only-be-used-as-a-generic-constraint-because-it-has-self-or-associa) for more info. – Sweeper Sep 01 '20 at 02:12
  • `decode` takes in a sequence of `Self.CodeUnit`s as the parameter. For `UTF8`, its code unit is `UInt8`. For `UTF32`, its code unit is `UInt32`. Without knowing what specific type `encodingStrToDecoder` returns, how do you know what to pass into `encode`? – Sweeper Sep 01 '20 at 02:16
  • Therefore, I suspect this is an [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). Can you show how you want to use the codec returned by `encodingStrToDecoder`? – Sweeper Sep 01 '20 at 02:19
  • @Sweeper I am trying to do this because I am trying to open a large file and I read it in chunks to save memory. However, If I run into a byte boundary with the chunks, I will have issues, so that's why I have to use the codec. I am planning to use it by iterating through an UnsafeMutablePointer – ABCD Man Sep 01 '20 at 02:31

0 Answers0