展平多維陣列
為了將多維陣列展平為單維,使用 flatMap 高階函式。其他用例是忽略陣列和對映值中的 nil 值。我們來看看例子: -
假設我們有一個多維的城市陣列,我們希望按升序排序城市名單。在這種情況下,我們可以使用 flatMap 函式,如: -
let arrStateName = [["Alaska", "Iowa", "Missouri", "New Mexico"], ["New York", "Texas", "Washington", "Maryland"], ["New Jersey", "Virginia", "Florida", "Colorado"]]
從多維陣列準備單維列表,
let arrFlatStateList = arrStateName.flatMap({ $0 }) // ["Alaska", "Iowa", "Missouri", "New Mexico", "New York", "Texas", "Washington", "Maryland", "New Jersey", "Virginia", "Florida", "Colorado"]
對於排序陣列值,我們可以使用連結操作或排序 flatten 陣列。下面的示例顯示了連結操作,
// Swift 2.3 syntax
let arrSortedStateList = arrStateName.flatMap({ $0 }).sort(<) // ["Alaska", "Colorado", "Florida", "Iowa", "Maryland", "Missouri", "New Jersey", "New Mexico", "New York", "Texas", "Virginia", "Washington"]
// Swift 3 syntax
let arrSortedStateList = arrStateName.flatMap({ $0 }).sorted(by: <) // ["Alaska", "Colorado", "Florida", "Iowa", "Maryland", "Missouri", "New Jersey", "New Mexico", "New York", "Texas", "Virginia", "Washington"]