Reputation: 778
Here I have a database, which I want to easily use for my table view. However, I can't reach the properties, because I don't know how to assign from a dictionary to a string. It tells me:
Cannot assign value of type 'Dictionary.Keys' to type 'String'
import Foundation
struct Test {
var title: String
var tagPreview: Tagpreview
}
struct Tagpreview {
var tag: [String?:String?]
}
var cases = [
Test(title: "title1", tagPreview: Tagpreview(tag: ["tag1": "preview1"])),
Test(title: "title2", tagPreview: Tagpreview(tag: ["tag2": nil])),
Test(title: "title3", tagPreview: Tagpreview(tag: [nil: nil])),
Test(title: "title4", tagPreview: Tagpreview(tag: ["tag4": "preview4", "tag5": nil]))
]
I want to use the keys and the values from the dictionary in the second struct to populate the text labels later in a cell:
cell.titleLabel?.text = cases[indexPath.row].tag.preview.keys //ERROR
cell.textLabel?.text = cases[indexPath.row].tag.preview.values//ERROR
There is something about dictionaries that I can't find anywhere as well as a comprehensive solution for this issue. Now, if you know another way how to populate them easily, I'd much appreciate that! Thank you a lot in advance and have a good day!
Upvotes: 3
Views: 4878
Reputation: 542
The error you are receiving is due to Dictionary.keys
returning a collection of the Type you selected as key. In your case the call cases[indexPath.row].tag.preview.keys
returns a Collection of String?
(similar to [String?]
)
Now if you wish to access a specific value from this collection, you should be able to do so like this:
let someText = cases[indexPath.row].tagPreview.tag.keys.map{ $0 }[someIndex]
Note that the use of map()
. It merely converts the Strings collection to an Array of Strings, whose index is Int, thus making it easier to access the individual elements (otherwise you'd need abit more general/cumbersome iteration API of Collection).
Just side comment, it seems a bit difficult to extract data and map it directly to the view, if you intend to use such mapping many places it may pay out to have some intermediate data types which are easier to use when presenting; it really depends on your preference and the overall problem.
Upvotes: 3