无法将struct数组插入一个数组中

时间:2015-10-18 23:26:23

标签: ios arrays swift struct

所以我有一个结构用于填充某些数组。

    let mcdonalds = restaurant(name: "Mcdonalds")
    let burgerking = restaurant(name: "Burger King")
    let vinsetta = restaurant(name: "Vinsetta Garage")
    let chinaone = restaurant(name: "China One Buffet")
    let pandaexpress = restaurant(name: "Panda Express")
    let olivegarden = restaurant(name: "Olive Garden")
    let salvatore = restaurant(name: "Salvatorre Scallopinis")


    american = [mcdonalds, burgerking]
    burgers = [vinsetta]
    chinese = [chinaone, pandaexpress]
    italian = [olivegarden, salvatore]
    allRestaurantTypeArray = [american, burgers, chinese, italian]

不幸的是,当我尝试将我的美国人,汉堡,中国人,和意大利阵列进入allrestaruranttypearray,我遇到了一个"不能分配类型" [[restaurant]]"类型值为#NSArray'"。

你能推荐任何改变吗?

更新

enter image description here

1 个答案:

答案 0 :(得分:1)

你可能想在这里flatMap ... enter image description here

您正在创建一个数组数组,这是[[restaurant]]的含义。

flatMap会“压扁”它们。

struct Restaurant {
    var name = ""
}
let mcdonalds = Restaurant(name: "Mcdonalds")
let burgerking = Restaurant(name: "Burger King")
let vinsetta = Restaurant(name: "Vinsetta Garage")
let chinaone = Restaurant(name: "China One Buffet")
let pandaexpress = Restaurant(name: "Panda Express")
let olivegarden = Restaurant(name: "Olive Garden")
let salvatore = Restaurant(name: "Salvatorre Scallopinis")


let american = [mcdonalds, burgerking]
let burgers = [vinsetta]
let chinese = [chinaone, pandaexpress]
let italian = [olivegarden, salvatore]
let allRestaurantTypeArray = [american, burgers, chinese, italian]

let flattened = allRestaurantTypeArray.flatMap{$0}



flattened.first?.name  // "Mcdonalds"
flattened.last?.name   // "Salvatorre Scallopinis"

我已将其更新为更好地帮助您:

enter image description here

您必须将flatmap应用于数组数组