首页 > 解决方案 > 函数式编程中非可选数组的可选对象

问题描述

我有一个 Type1 的可选 object1。我想将它转换为 Type2 的数组(非可选,如果 object1 为 nil,则为空)。

Type2 对象由 Type1 对象构成。

所以我试过这样:


func convert(object1: Type1?) -> [Type2] {
    object1.map {
        [
         Type2($0)
        ] 
    }
}

但我得到这个错误:

Cannot convert return expression of type '[Type2]?' to return type '[Type2]'

注意:Type2 初始化程序不能将可选值作为参数。

如果有人有想法,请提前致谢

标签: iosswiftfunctional-programming

解决方案


尝试

func convert(object1: Type1?) -> [Type2] {
    guard let res = object1 else { return [] }
    return [Type2(res)]
}

推荐阅读