writeClassDecode method

  1. @override
void writeClassDecode(
  1. SwiftOptions generatorOptions,
  2. Root root,
  3. Indent indent,
  4. Class classDefinition, {
  5. required String dartPackageName,
})
override

Writes a single class decode method to indent.

Implementation

@override
void writeClassDecode(
  SwiftOptions generatorOptions,
  Root root,
  Indent indent,
  Class classDefinition, {
  required String dartPackageName,
}) {
  final String className = classDefinition.name;
  indent.writeln('// swift-format-ignore: AlwaysUseLowerCamelCase');
  indent.write(
      'static func fromList(_ ${varNamePrefix}list: [Any?]) -> $className? ');

  indent.addScoped('{', '}', () {
    enumerate(getFieldsInSerializationOrder(classDefinition),
        (int index, final NamedType field) {
      final String listValue = '${varNamePrefix}list[$index]';

      _writeGenericCasting(
        indent: indent,
        value: listValue,
        variableName: field.name,
        fieldType: _swiftTypeForDartType(field.type),
        type: field.type,
      );
    });

    indent.newln();
    indent.write('return ');
    indent.addScoped('$className(', ')', () {
      for (final NamedType field
          in getFieldsInSerializationOrder(classDefinition)) {
        final String comma =
            getFieldsInSerializationOrder(classDefinition).last == field
                ? ''
                : ',';
        // Force-casting nullable enums in maps doesn't work the same as other types.
        // It needs soft-casting followed by force unwrapping.
        final String forceUnwrapMapWithNullableEnums =
            (field.type.baseName == 'Map' &&
                    !field.type.isNullable &&
                    field.type.typeArguments
                        .any((TypeDeclaration type) => type.isEnum))
                ? '!'
                : '';
        indent.writeln(
            '${field.name}: ${field.name}$forceUnwrapMapWithNullableEnums$comma');
      }
    });
  });
}