I'm trying to translate javascript to swift. This is the javascript method:
export function serializeProperty(
properties: Map<Key, Value | null>,
): Array<[Key, JsonValue | null]> {
const data = Array.from(properties.entries());
const processedData = data.map(entry => {
const [key, value] = entry;
if (value != null) {
return [key, serializeValue(value)];
}
return [key, null];
});
return processedData;
}
export function serializeValue(Value: Value): JsonValue {
if (Value.type === 'string') {
return {type: 'string', value: Value.value.toJson()};
} else if (Value.type === 'array_node') {
return {
type: 'array_node',
value: Value.value.map(node => node.toJson()),
};
}
return Value;
}
I have translated it in swift like below:
func serializeProperty(properties: [Key: Value?]) -> [[Key: JsonValue?]]? {
var data: [[Key: JsonValue?]]?
guard let propertiesJson = properties else { return data }
for property in propertiesJson {
for item in property {
if let unwrappedValue = item.value {
properties[item.key] = try serializeValue(valueJson: unwrappedValue)
}
}
}
return data
}
I'm getting the error on this line : guard let propertiesJson = properties else { return data }
Is the translation to swift correct or am I missing something?
The simplest translation of this TypeScript to Swift will look something like:
Note the use of
(Key, JsonValue?)in regular parentheses to denote a tuple ofKeyandJsonValue?, matching the TypeScript notation of[Key, JsonValue | null]. Also note that in both the TypeScript and Swift implementations, thepropertiesparameter is a non-nullable type, so there is no need to check againstnull/nil.Using a guard clause and returning the result of
properties.map()directly, this can be further simplified to:Going back the other way, the TypeScript implementation can also be simplified in a similar way to: