解決方法1(這是swiftiest方式):
//if you want to keep adding to the old array
allItems += allPeople.flatMap{$0.items}
//if you want to add into a new array
let newArray = allItems + allPeople.flatMap{$0.items}
// Using 'map' won't work:
allItems = allItems + allPeople.map{$0.items} //error: binary operator '+' cannot be applied to operands of type '[String]' and '[[String]]'
上面的代碼不工作,因爲我們正在增加[String]]
到[String]
該+
不知道如何處理,請閱讀:
let john = Person()
john.items = ["a", "b", "c"]
let jane = Person()
jane.items = ["d", "e", "f"]
allPeople.append(john)
allPeople.append(jane)
print(allPeople.map{$0.items}) // [["a", "b", "c"], ["d", "e", "f"]] <-- [[String]]
// and obviously can't be added to [String]
據內部印刷陣列陣列。所以我們需要再做一步。
let mapped = allPeople.map{$0.items}
print(Array(mapped.joined())) // ["a", "b", "c", "d", "e", "f"]
所以,如果我們要使用map
,我們也應該用joined
溶液2(不是很SWIFTY但我只是想多解釋flatMap
基本上是一個join
+ map
)
let newJoinedMappedArray = allItems + Array(allPeople.map($0.items).joined())
怎麼樣'let allItems = allPeople.flatMap {$ 0.items}'? – sbooth
您並未將它們添加/附加在一起。雖然很好地使用了'flatmap'。我正在使用'map'這是不正確的... – Honey
請描述你想要達到的目標,你嘗試過什麼以及目前的結果(問題)是什麼。 – shallowThought