[Solved] How can i parse this respose to my Array of string


Optional("[\n  \"Aircel\",\n  \"Airtel\",\n  \"BSNL\",\n  \"Idea MTV\",\n  \"MTNL\",\n  \"MTS\",\n  \"Reliance CDMA\",\n  \"Reliance GSM\",\n  \"Reliance JIO\",\n  \"TATA CDMA\",\n  \"TATA DOCOMO\",\n  \"Telenor\",\n  \"Videocon\",\n  \"Vodafone\"\n]")

is the same as this, just to visualize the data a little bit better

Optional("[  
              \"Aircel\",
              \"Airtel\",
              \"BSNL\",
              \"Idea MTV\",
              \"MTNL\",
              \"MTS\",
              \"Reliance CDMA\",
              \"Reliance GSM\",
              \"Reliance JIO\",
              \"TATA CDMA\",
              \"TATA DOCOMO\",
              \"Telenor\",
              \"Videocon\",
              \"Vodafone\"
            ]")

Since the data is optional it we should check if it exists and if it does start parsing. This can be done using the following syntax:

if let a = optional_a {

}

where optional_a can be any optional datatype and a is nonoptional. Basically Swift checks if it is nil and if not assigns it to a.

Next for the parsing, the String class has a function called replacingOccurences(of: String!, with String!). Think of this as a find and replace all function. This can be used to remove any extraneous characters such as “\n”, “\””, “\”, “[“, “]”, and ” “. Once these are removed we need to split the string with “,” and map it into an array.

This code should work:

var optionalResponse = Optional("[\n  \"Aircel\",\n  \"Airtel\",\n  \"BSNL\",\n  \"Idea MTV\",\n  \"MTNL\",\n  \"MTS\",\n  \"Reliance CDMA\",\n  \"Reliance GSM\",\n  \"Reliance JIO\",\n  \"TATA CDMA\",\n  \"TATA DOCOMO\",\n  \"Telenor\",\n  \"Videocon\",\n  \"Vodafone\"\n]")
if var response = optionalResponse {
    let charsToRemove = ["\n", "\"", "\\", "[", "]", " "]
    for char in charsToRemove {
        response = response.replacingOccurrences(of: char, with: "")
    }
    let fullNameArr = response.characters.split{$0 == ","}.map(String.init)

    print(fullNameArr)
}

1

solved How can i parse this respose to my Array of string