[Swift] Required fields have default values in generated Swift code.
kennycarruthers opened this issue · comments
Given the following schema:
struct Position {
x: int64;
}
table Weapon {
strength: int64;
}
table Entity {
id: int64;
position: Position (required);
weapon: Weapon (required);
}
The Swift generated code uses force unwrapping for the required fields, but uses default values in initializers and constructors, effectively making the required fields optional.
public struct Entity: FlatBufferObject, Verifiable, ObjectAPIPacker {
// snip...
// Optionals are force-unwrapped here.
public var position: Position! { let o = _accessor.offset(VTOFFSET.position.v); return _accessor.readBuffer(of: Position.self, at: o) }
public var weapon: Weapon! { let o = _accessor.offset(VTOFFSET.weapon.v); return Weapon(_accessor.bb, o:
// Note optional parameter for required field `position`.
public static func add(position: Position?, _ fbb: inout FlatBufferBuilder) { ...}
// Note non-optional parameter for required field `weapon`.
public static func add(weapon: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: weapon, at: VTOFFSET.weapon.p) }
// Note optional parameter and default values for `position` and default value for `weaponOffset`.
public static func createEntity(
_ fbb: inout FlatBufferBuilder,
id: Int64 = 0,
position: Position? = nil,
weaponOffset weapon: Offset = Offset()
) -> Offset {
let __start = Entity.startEntity(&fbb)
Entity.add(id: id, &fbb)
Entity.add(position: position, &fbb)
Entity.add(weapon: weapon, &fbb)
return Entity.endEntity(&fbb, start: __start)
}
// snip ...
}
Is this the intended behaviour? At least in the Swift implementation, the current behaviour allows the caller to create a new FlatBuffer without specifying a value for a required field.
(Or is "nil" considered a valid value for a required field within the world of FlatBuffers?)
Hey, thanks for opening the issue!
Looks like a bug to me (at least in the createEntity
function. since that should not allow the user to create default fields if they are required.
@kennycarruthers Regarding this issue after looking into it a bit
We do verify if the fields are added when we run endMonster
which runs fbb.require(table: end, fields: [10]);
and thus we don't really need to make the functions require the value. However, it seems that the proper approach would be fixing it