簡體   English   中英

無法指定“字典”類型的值 <String?, String?> .Keys&#39;鍵入&#39;String&#39;

[英]Cannot assign value of type 'Dictionary<String?, String?>.Keys' to type 'String'

這里我有一個數據庫,我想輕松地用於我的表視圖。 但是,我無法訪問屬性,因為我不知道如何從字典分配給字符串。 它告訴我:

無法將“Dictionary.Keys”類型的值指定為“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]))
]

我想使用第二個結構中的字典中的鍵和值來稍后在單元格中填充文本標簽:

cell.titleLabel?.text = cases[indexPath.row].tag.preview.keys //ERROR
cell.textLabel?.text = cases[indexPath.row].tag.preview.values//ERROR

關於字典,我找不到任何地方,以及針對此問題的綜合解決方案。 現在,如果您知道如何輕松填充它們的另一種方式,我會非常感激! 非常感謝你,祝你有個美好的一天!

您收到的錯誤是由於Dictionary.keys返回您選擇為鍵的類型的集合。 在您的情況下,調用cases[indexPath.row].tag.preview.keys返回一個String?集合String? (類似於[String?]

現在,如果您希望從此集合中訪問特定值,您應該能夠這樣做:

let someText = cases[indexPath.row].tagPreview.tag.keys.map{ $0 }[someIndex]

注意使用map() 它只是將Strings集合轉換為一個字符串數組,其索引為Int,從而更容易訪問各個元素(否則你需要abit更通用/繁瑣的Collection迭代API)。

只是側面評論,提取數據並將其直接映射到視圖似乎有點困難,如果您打算使用這樣的映射許多地方可能需要付出一些中間數據類型,這些類型在呈現時更容易使用; 這真的取決於你的偏好和整體問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM