Home > Software design >  How to write condition in struct
How to write condition in struct

Time:02-14

Based on condition, how to set Array of Dictionary else only Dictionary for struct.

   struct Data {
        let id: String?
        let name: String?
        let subData:  Environment.Dev == "Dev_URL" ? [SubData]? : SubData?
    
        init(_ json: JSON) {
            id = json["id"].stringValue
            name = json["name"].stringValue
            subData =  Environment.Dev == "Dev_URL" ? json["sub_data"].arrayValue.map { SubData($0) } : SubData(json["sub_data"])
        }
    }

// SubData Struct

   struct SubData {
        let id: String?
        init(_ json: JSON) {
            id = json["id"].stringValue
   }
}

My response structure changes due to environment changes.

How to set struct Data for let subData [SubData] i.e array of dictionary else SubData normal dictionary based on Dev or other.

CodePudding user response:

An easy way to make it array in both cases as type can't be determined at runtime

let subData:[SubData]?

Then

subData =  Environment.Dev == "Dev_URL"              
            ? json["sub_data"].arrayValue.map { SubData($0) }
            : [SubData(json["sub_data"])]

Also you can change your response sub_data to be an array in both cases so above line be

subData = json["sub_data"].arrayValue.map { SubData($0) }

That way you work in development and release smoothly

  • Related