I am trying to integrate SwiftData for storing data in my app, which currently uses objectmapper along with alamofire for mapping json data into models. For using swiftData, it requires that the models confer to Codable protocol. This is a bit tricky for me to achieve as currently, my project requires extensive use of Any for storing data in models which vary at run time and can be nested. The solution i am finding online requires me to create my own struct which takes a parameter as Any, and manually writing encoding and decoding functions by confering to codable protocol. This is a valid solution however, it would require me to complete re-write majority of the business logic in my app that uses Any currently. So I am finding a work-around or alternate solution for the same.
typealias asDictionary = [String : Any]
static func getSingleLevelDictFromNestedDict(dict: asDictionary, fieldId: String? = nil, index: Int = 0, parentKey: String? = nil) -> asDictionary {
var singleLevelDict = asDictionary()
for (key,value) in dict {
var updatedKey = key
if let fieldId = fieldId {
updatedKey = "(fieldId).(index).(key)"
} else if let parentKey = parentKey {
updatedKey = "(parentKey).(key)"
}
if let nestedDictArray = value as? [asDictionary], !nestedDictArray.isEmpty {
for (nestedIndex, nestedDict) in nestedDictArray.enumerated() {
let nestedConvertedDict = getSingleLevelDictFromNestedDict(dict: nestedDict, parentKey: "(updatedKey).(nestedIndex)")
singleLevelDict.merge(nestedConvertedDict) { current, _ in
return current
}
}
} else if var nestedDict = value as? asDictionary, !nestedDict.isEmpty {
if key == SubSectionType_v3.descriptionWithFiles.rawValue || key == SubSectionType_v3.content.rawValue {
let files = nestedDict["files"] as? [Files]
nestedDict["files"] = files?.toJSON()
}
let nestedConvertedDict = getSingleLevelDictFromNestedDict(dict: nestedDict, parentKey: updatedKey)
singleLevelDict.merge(nestedConvertedDict) { current, _ in
return current
}
} else {
singleLevelDict[updatedKey] = value
}
}
return singleLevelDict
}
I wanted a solution so that without changing my code base I can use any with Codable in swift or SwifUI