If you're trying to encode multiple values of different types conforming to Encodable, the feature you're looking for is called variadic generics, which is not yet implemented.
If you're trying to encode multiple values all of the same type conforming Encodable, the solution is somewhere between what you've written as your two code samples:
It should let you write the method as func encodeAndMerge(_ value: AnyCodable...) throws -> [String: Any] { ... }, with an implementation mostly identical to the example you included.
You can then use it in your encodeAndMerge function:
func encodeAndMerge(_ values: Codable...) throws -> [String: Any] {
let encoder = JSONEncoder()
let result: [String: Any] = try values.reduce([String: Any]()) { runningResult, codable in
let data = try encoder.encode(AnyEncodable(value: codable))
guard let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: Any] else {
return runningResult
}
return runningResult.merging(json, uniquingKeysWith: { $1 })
}
return result
}
Without the box, Swift will give an error: error: protocol type 'Codable' (aka 'Decodable & Encodable') cannot conform to 'Encodable' because only concrete types can conform to protocols which is what I'm guessing you were getting in your code...
But I don't know exactly why it allows initializing AnyEncodable(value: Encodable) with a protocol type.
won't quite give you what you want in all cases because it doesn't give an Encoder a chance to intercept the value before it encodes its contents. This is important for encoding strategies to apply (e.g. JSONEncoder.dateEncodingStrategy), which means that you could have inconsistent application of the strategy across your archive. @hamishknight's approach approach will more consistently give you the results you're looking for.