Dictionary String:AnyObject

Hello dear readers,

I’m having an issue with dictionaries.
I have a this: Key0:Value\nKey1:Value\nKey2:Value\nKey3:Value\n
I would like to create a dictionary with these keys and values.

I have written this code for now:

let deciphered = str.split(separator: "\n").reduce(into: [String: AnyObject]()) {
    let str = $1.split(separator: ":")

    if let first = str.first, let key = String(first), let value = str.last {
        $0[key] = value as AnyObject
    }
}```
But I'm having this error:
```**error: initializer for conditional binding must have Optional type, not 'String'**
**if let first = str.first, let key = String(first), let value = str.last {**
                              ^   ~~~~~~~~~~~~~

Can you help me or give me an other way to store it ?

@pauldance Here is the updated version of your code that does exactly what you want in this case:

let deciphered = str.split(separator: "\n").reduce(into: [:]) { // 1
  let element = $1.split(separator: ":") // 2
  if let key = element.first, let value = element.last { // 3
    $0[key] = value // 4
  }
}

Going through the above changes step by step:

  1. Use type inference to create an empty dictionary of type [String: String].
  2. Use element instead of str for the dictionary elements to avoid confusion between the initial string and its parsed elements.
  3. Remove key conversion to String since key is already of type String in this case.
  4. Remove value cast to AnyObject since value is of type String in this case.

Please let me know if you have any other questions or issues about the whole thing when you get a chance. Thank you!

Hello @shogunkaramazov,

Thank you for your reply and your explications.

var data = "Key0:Value\nKey1:Value\nKey2:Value\nKey3:Value\n"
var deciphered = data.split(separator: "\n").reduce(into: [String: String]()) {
            let str = $1.split(separator: ":")
            if let first = str.first, let value = str.last {
                $0[String(first)] = String(value)
            }
        }

I’m going with this modified version. I don’t want to have the AnyHashable

The little issue I’m facing now, is to display the dictionary. I’m using SwiftUI for my app UI.

here is the code:

struct NFCMobileView: View {
    @Binding var data: String
    var body: some View {
        var deciphered = data.split(separator: "\n").reduce(into: [String: String]()) {
            let str = $1.split(separator: ":")
            if let first = str.first, let value = str.last {
                $0[String(first)] = String(value)
            }
        }
        HStack {
            Text("Last Name")
            TextField("", text: deciphered["lastName"]) // error
        }
    }
}

Cannot convert value of type 'String?' to expected argumument type 'Binding<String>'
this is the error I’m having

This topic was automatically closed after 166 days. New replies are no longer allowed.