如何从函数中将任何 Codable Struct 作为 return 传递并在 JSONEncoder 中使用它

How to pass any Codable Struct as a return from function and use it in JSONEncoder

作为网络请求的一部分,我想将 Codable 中的任何 struct 传递给 JSONEncoder().encode 函数。当我直接传递对象时,可以说

struct MyObject: Codable {}
 func createData<T:Codable>(objectToEncode: T) {
       JSONEncoder().encode(T)
       }
 func assigningObject() {
        createData(objectToEncode: MyObject())
         }

它工作得很好,但是我不知道如何传递作为函数输出的任何可编码对象,当我调用时让我们说:

 func createObject() -> Codable {
      return MyObject()
     }
    
 func assigningObject() {
       let myReturnObject = createObject()
       createData(objectToEncode: myReturnObject)
       }

我无法执行 createData(objectToEncode: myReturnObject) ,因为编译器显示错误 Value of protocol type 'Codable' (aka 'Decodable & Encodable') cannot conform to 'Decodable'; only struct/enum/class types can conform to protocols

有什么方法可以return从函数构造对象吗?

iOS 13 及更高版本的解决方案是使用不透明类型:

func createObject() -> some Codable