[flatMap]对Optional类型进行flatMap的实验(上)

  • Optional不解包,直接使用flatMap的话,返回的对象依然是Optional
//例子一
let num:Int? = nil
let flatMapNum = num.flatMap{ $0 }  //nil
type(of: flatMapNum)        //Optional

//例子二
let array:[Int]? = [1, 2, 3]
type(of: array.flatMap{ $0 })  // Optional>
array.flatMap{ $0 }         // Optional([1, 2, 3])

  • 先强制解包,再使用flatMap,则不会有上述问题(都强制解包了当然没问题...)
//例子二的变种
let array:[Int]? = [1, 2, 3]
type(of: array!.flatMap{ $0 })  // Array
array!.flatMap{ $0 }            // [1, 2, 3]
  • 如Optional实际值为nil,则flatMap后结果也为nil
let array:[Int]? = nil
type(of: array.flatMap{ $0 })  // Optional> 但值为nil
array.flatMap{ $0 }         // nil
  • flatMap可以过滤元素为Optional的数组中的nil,并且安全解包
let array: [Int?] = [1, 2, 3, 4, 5, nil, 8]
array.flatMap{ $0 }  //[1, 2, 3, 4, 5, 8]

array.forEach{ print(type(of: $0)) } //输出N个Optional
let arrayFlatMap = array.flatMap{ $0 }  //[1, 2, 3, 4, 5, 8]
arrayFlatMap.forEach{ print(type(of: $0)) } //输出N个Int

众所周知,flatMap还可以扁平化数组,达到给多维数组降维的目的:

let array: [[Int]] = [[1, 2, 3], [4, 5, 6]]
print(array.flatMap{ $0 }) //[1, 2, 3, 4, 5, 6]

那么如果Optional配上多维数组,会是如何的结果呢......?

各位看官请看题:


//请用flatMap扁平化以下所有数组,不允许强制解包(如值为nil会崩掉的...)
let array1:[[Int]] = [[1, 2, 3], [4, 5, 6]]
let array2:[[Int]]? = [[1, 2, 3], [4, 5, 6]]
let array3:[[Int]?] = [[1, 2, 3], [4, 5, 6]]
let array4:[[Int]?]? = [[1, 2, 3], [4, 5, 6]]
let array5:[[Int?]] = [[1, 2, 3], [4, 5, 6]]
let array6:[[Int?]]? = [[1, 2, 3], [4, 5, 6]]
let array7:[[Int?]?] = [[1, 2, 3], [4, 5, 6]]
let array8:[[Int?]?]? = [[1, 2, 3], [4, 5, 6]]

鬼???

这是答案

你可能感兴趣的:([flatMap]对Optional类型进行flatMap的实验(上))