字典地图认为字符串是字符串数组

时间:2018-08-04 04:31:53

标签: swift dictionary

struct Item2 {
    var itemid: Int
    var category_id: Int
    var category_name: String
    var name: String
}

struct Item{
    var name = String()
    var rows = [Row]()
}

struct Row{
    var size: Int
}

struct Collapsed{
    var category_opened = Bool()
    var category_id = Int()
    var category_name = String()
    var items = [Item]()
}

let menu2 = [
    Item2(itemid: 5, category_id: 0, category_name: "category1", name: "item1"),
    Item2(itemid: 2, category_id: 0, category_name: "category1", name: "item2"),
    Item2(itemid: 3, category_id: 0, category_name: "category1", name: "item3"),
    Item2(itemid: 1, category_id: 1, category_name: "category2", name: "item4"),
    Item2(itemid: 7, category_id: 1, category_name: "category2", name: "item5"),
    Item2(itemid: 9, category_id: 1, category_name: "category2", name: "item6")]

let mapping = Dictionary(grouping: menu2, by: { $0.category_id })
// Map that dictionary into an array of Sorted and then sort that array by category_id
let collapsedItems: [Collapsed] = mapping.map {
    Collapsed(
        category_opened: false,
        category_id: $0.key,
        category_name: $0.value.map { $0.category_name }, // Error: Cannot convert value of type '[String]' to expected argument type 'String'
        items: $0.value.map { $0.name }
    )
}
.sorted { $0.category_id < $1.category_id }

我正在尝试用字典重新组织数据,但是从底部开始的第5行给出错误为:

  

无法将类型“ [String]”的值转换为预期的参数类型“ String”

据我所知,Collapsed.category_nameItem2.category_name都是字符串,那么问题是什么?

1 个答案:

答案 0 :(得分:1)

错误很明显。

  

无法将类型“ [String]”的值转换为预期的参数类型“ String”

此行代码names将返回hobbies,您正在根据添加的数据使用属性names对其进行设置,该属性的类型为$0.value.map { $0.category_name }。在 menu2 数组中,您需要设置的是分组字典中第一个对象的category_name,因为[String]category_name属于彼此。

因此代替

String

您需要拥有

category_id

解决此问题后,您会在第category_name行获得错误

  

无法将类型“ [String]”的值转换为预期的参数类型“ [Item]”

因此代替

category_name: $0.value.map { $0.category_name },

您需要拥有

category_name:  $0.value.first?.category_name ?? "", 
// You can force wrap the first property too as of you have make dictionary using grouping it will at least have single object.