I'm trying to create an object of this class where related_item
is an optional array which have same properties of its class, when I create an instance of this class my app crash and point to related_item
without giving any error eplaniton, what the correct way to make such class, and an instance of it, or an array of SoundModel
type?
class SoundModel:Codable
{
var sort : String? = ""
var type : String? = ""
var name : String? = ""
var pic_file_path : String? = ""
var text : String? = ""
var related_item : [SoundModel?] = [SoundModel()]
}
You're running off the end of your call stack, because your initialization of SoundModel
is recursive. When you create a SoundModel
instance, that creates another one (for the related_item
array), which creates another one, and so on, forever or until the stack overflows.
What are you really trying to do, in terms of related items? Do you actually need to put anything in the related_item
array when an instance is created?
I’m trying to convert bellow response to codable object
[
{
"sort": "0",
"type": "sec_list",
"name": "Marj",
"pic_file_path": null,
"text": "",
"related_item": [
{
"sort": "3",
"type": "sec_list",
"name": "simple ",
"pic_file_path": null,
"text": ""
}
]
}
]
In that case (based on just the information you've given) the struct should look something like this:
class SoundModel:Codable
{
var sort : String? = ""
var type : String? = ""
var name : String? = ""
var pic_file_path : String? = ""
var text : String? = ""
var related_item : [SoundModel]? = nil
}
I changed 2 things:
-
The
related_item
array is optional, so that you know whether that information was present in the JSON. (It seems wrong to make it an array of optionals.) -
The
related_item
array is nil by default. It will only be non-nil if the JSON key is present, and it will get members as specified by what's in the JSON.