0

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.

1
  • 1
    Try to use parentheses, let imageUrl = baseURL + (imageArr?[2] as! String). Commented Sep 12, 2022 at 20:42

1 Answer 1

1

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.

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

Comments

Your Answer

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