简体   繁体   English

可选 object 到函数式编程中的非可选数组

[英]Optional object to non-optional Array in functional programming

I have an optional object1 of Type1.我有一个 Type1 的可选 object1。 I would like to convert it to an array of Type2 (non optional, empty if object1 was nil).我想将它转换为 Type2 的数组(非可选,如果 object1 为 nil,则为空)。

Type2 objects are constructed with Type1 objects. Type2 对象由 Type1 对象构成。

So I've tried like this:所以我试过这样:


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

But I get this error:但我得到这个错误:

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

Note: Type2 initialiser cannot take a an optional value as parameter.注意:Type2 初始化程序不能将可选值作为参数。

if anyone has an idea, thanks in advance如果有人有想法,请提前致谢

Try尝试

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

The error you are getting means that when you map an optional value you will either get the result of mapping (array of Type2 indoor example) or nil if the initial value (object) was nil.您收到的错误意味着当您使用 map 一个可选值时,您将获得映射结果(Type2 室内示例数组),或者如果初始值(对象)为 nil,则为 nil。 In such a case you could use nil coalesing operator to give a value to replace nil (in this case an empty array):在这种情况下,您可以使用 nil 合并运算符给出一个值来替换 nil(在这种情况下是一个空数组):

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

Another possible approach would be:另一种可能的方法是:

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

        class Type2 {
            init(_ type1: Type1) {
            }
        }

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM