user19949483
user19949483

Reputation:

How to convert dictionary array into String?

I have a base URL:

let baseURL = "https://t**.com"

I am receiving a dictionary, in which I have a method name, HubName, and an array which contains the data.

if let values = data as? [String: Any] {
            print("Method Name is: \(values[Types.method]!), Hubname: \(values[Types.hubName]!), messageReceived: \(values[Types.array]!)") }

Here is the response I get when I send a picture from the server:

Method Name is: ImageFromAgent, Hubname: NotificationHub, messageReceived: (
"Admin User",
16406,
"/api/WebChat/GetUpload?path=97511d99-887f-4ab9-96ac-d372d542097e-Screenshot 2022-09-07 at 7.36.05 PM.png"

)

Now in second index of Array, I have an image path which I want to append with my baseURL.

What Im trying is:

            if values[Types.method] as! String == MethodName.ImageFromAgent {
                let imageArr = values[Types.array] as? [Any]
                let imageUrl = baseURL + imageArr?[2] as! String
                print("imageUrl = \(imageUrl)")
            }

However, it is not converting it into a string and receiving error of Binary operator '+' cannot be applied to operands of type 'String' and 'Any?'

If I do:

if values[Types.method] as! String == MethodName.ImageFromAgent {
                let imageArr = values[Types.array] as? [Any]
                print("imageUrl = \(imageArr![2])")
            }

Then I receive the image path, but I want to join the baseURL and the file path into a single string.

Upvotes: 0

Views: 71

Answers (1)

Vikram Parimi
Vikram Parimi

Reputation: 777

If you use optional unwrapping you can use ? operator to safely unwrap the value and there won't be a type inference problem

The below should solve your problem

if values[Types.method] as! String == MethodName.ImageFromAgent {
            if let imageArr = values[Types.array] as? [Any],
            let imageURlString = imageArr[2] as? Sting {
            let imageUrl = baseURL + imageURlString
            print("imageUrl = \(imageUrl)")
        }

Using a force-unwrap operator can crash your app abruptly. Also, you are using the index 2 and !.

Also, as a best practice try avoid force-unwrap unless you are sure there will be a non-null value all the time.

Upvotes: 1

Related Questions