0

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.

2
  • 2
    You cannot change type of a variable depending on a runtime condition. Commented Feb 13, 2022 at 17:07
  • Use an enum with associated values, where one case has SubData as its associated type and the other has [SubData] Commented Feb 13, 2022 at 19:02

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

@thanks khan. is sh_ Shah Rukh?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.