Hello dear readers,
I'm having an issue with dictionaries.
I am receiving this from my NDEF tag: Key0:Value\nKey1:Value\nKey2:Value\nKey3:Value\n
The values can be ether String or Int.
I would like to create a dictionary with these keys and values.
I have written this code for now:
I also tried this:
Where str is my string of all values. But I'm stuck with the : between the Key and Value
But I'm having this error:
Can you help me or give me an other way to store it ?
The idea after is to modify the value and send it back on a NDEF tag.
Thank you for your help
I'm having an issue with dictionaries.
I am receiving this from my NDEF tag: Key0:Value\nKey1:Value\nKey2:Value\nKey3:Value\n
The values can be ether String or Int.
I would like to create a dictionary with these keys and values.
I have written this code for now:
Code Block Swift 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 } }
I also tried this:
Code Block let split = str.split(whereSeparator: \.isNewline)
Where str is my string of all values. But I'm stuck with the : between the Key and Value
But I'm having this error:
Code Block 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 ?
The idea after is to modify the value and send it back on a NDEF tag.
Thank you for your help
You can write your code without using let key:
If you insist on using let key, you can write it as:
If you dare move it inside if:
But I do not recommend this as case let key = String(first) is not working as a condition.
Code Block import Foundation let str = "Key0:Value\nKey1:Value\nKey2:Value\nKey3:Value\n" let deciphered = str.split(separator: "\n").reduce(into: [String: AnyObject]()) { let str = $1.split(separator: ":") if let first = str.first, let value = str.last { $0[String(first)] = value as AnyObject } } print(deciphered) //-> ["Key0": Value, "Key1": Value, "Key3": Value, "Key2": Value]
If you insist on using let key, you can write it as:
Code Block let deciphered = str.split(separator: "\n").reduce(into: [String: AnyObject]()) { let str = $1.split(separator: ":") if let first = str.first, let value = str.last { let key = String(first) $0[key] = value as AnyObject } }
If you dare move it inside if:
Code Block let deciphered = str.split(separator: "\n").reduce(into: [String: AnyObject]()) { let str = $1.split(separator: ":") if let first = str.first, case let key = String(first), let value = str.last { $0[key] = value as AnyObject } }
But I do not recommend this as case let key = String(first) is not working as a condition.