i have a type BSON.Fields
, which is ExpressibleByDictionaryLiteral
:
extension BSON.Fields:ExpressibleByDictionaryLiteral
{
@inlinable public
init(dictionaryLiteral:(String, BSON.Value<[UInt8]>)...)
{
self.init(dictionaryLiteral)
}
}
it also conforms to a protocol BSONEncodable
:
extension BSON.Fields:BSONEncodable
{
...
}
finally, it has a subscript that can be assigned to with some optional BSONEncodable
value:
extension BSON.Fields
{
@inlinable public
subscript<Encodable>(key:String) -> Encodable?
where Encodable:BSONEncodable
{
get
{
nil
}
set(value)
{
...
}
}
}
based on this, i would expect it to be possible to assign to this subscript with a dictionary literal, which should generate a nested instance of BSON.Fields
.
this works:
outer["a"] = ["a": 1, "b": 2, "c": 3] as BSON.Fields
but this doesn’t:
outer["b"] = ["a": 1, "b": 2, "c": 3]
// ^~~~~~~~~~~~~~~~~~~~~~~~
// error: cannot assign value of type '[String : Int]' to subscript
// of type 'Encodable'
the fixit is quite perplexing:
Tests/BSONEncoding/Main.swift:44:21:
error: generic parameter 'Encodable' could not be inferred
outer["b"] = ["a": 1, "b": 2, "c": 3]
^
Sources/BSONEncoding/Encoding/BSON.Fields.swift:12:5:
note: in call to 'subscript(_:)'
subscript<Encodable>(key:String) -> Encodable?
where Encodable:BSONEncodable
^
Tests/BSONEncoding/Main.swift:44:31:
error: cannot assign value of type '[String : Int]' to subscript
of type 'Encodable'
outer["b"] = ["a": 1, "b": 2, "c": 3]
^~~~~~~~~~~~~~~~~~~~~~~~
as! Encodable
because the type is not Encodable
, it is some BSONEncodable
and Encodable
is just the name of the generic parameter, and force-casting with as! Encodable
will not help.
curiously, array literals do not have this problem:
outer["c"] = [1, 2, 3]
because Array
is BSONEncodable
:
extension Array:BSONEncodable where Element:BSONEncodable
{
...
}
and Array
can come from an array literal without an as
coercion.