From bd1e64caa1db0d703a04c786bd02e7a98704618c Mon Sep 17 00:00:00 2001 From: Madhas Date: Tue, 5 Jun 2018 18:59:38 +0300 Subject: [PATCH] fix optional decoding --- Swift/macroses/common.utils.twig | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/Swift/macroses/common.utils.twig b/Swift/macroses/common.utils.twig index a5eab6e..65233d1 100644 --- a/Swift/macroses/common.utils.twig +++ b/Swift/macroses/common.utils.twig @@ -74,7 +74,7 @@ {% elseif field.type.type.baseTypeName == "Decimal" %} {{ self.decodeComplexField(field, "Decimal") }} {%- else -%} - self.{{ field.name }} = {{ self.formatNullableOrOptional("try", field.nullable, field.optional) }} container.decode({{ self.formatValueType(field.type.type) }}.self, forKey: .{{ field.name }}) + self.{{ field.name }} = try container.{{- self.formatOptionalDecode(field) -}}({{ self.formatValueType(field.type.type) }}.self, forKey: .{{ field.name }}) {%- endif -%} {% endmacro %} @@ -82,7 +82,7 @@ {%- import _self as self -%} {%- if field.optional or field.nullable -%} - if let {{ field.name }} = try? container.decode({{ decodingType }}.self, forKey: .{{ field.name }}) { + if let {{ field.name }} = try container.decodeIfPresent({{ decodingType }}.self, forKey: .{{ field.name }}) { {{ self.initExpr(field) }} } else { self.{{ field.name }} = nil @@ -93,6 +93,14 @@ {%- endif -%} {% endmacro %} +{% macro formatOptionalDecode(field) %} + {%- if field.optional or field.nullable -%} + decodeIfPresent + {%- else -%} + decode + {%- endif -%} +{% endmacro %} + {% macro initExpr(field) %} {%- if field.type.type.baseTypeName == "DateTime" -%} if let date = DateInRegion(string: {{ field.name }}, format: ApiDateFormat.{{ dateFormatToName(field.type.dateFormat) }}.swiftDateFormat, fromRegion: ApiDateFormattingService.shared.currentRegion) {