展平多维数组
为了将多维数组展平为单维,使用 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"]