0

I have an optional object1 of Type1. I would like to convert it to an array of Type2 (non optional, empty if object1 was nil).

Type2 objects are constructed with Type1 objects.

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.

if anyone has an idea, thanks in advance

1
  • So, type1 is array and it can have optional values, and you want to convert it into second array of all non-optional values am I right? Commented Jun 4, 2021 at 15:02

3 Answers 3

1

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. In such a case you could use nil coalesing operator to give a value to replace nil (in this case an empty array) :

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) }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I was looking for something like the second approach !
1

Try

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

2 Comments

Type2 initialiser cannot take a an optional value as parameter.
Cannot convert value of type 'Type1?' to expected element type 'Type1'
0
        class Type1 {}

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

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

1 Comment

I think compactMap is much simpler to read solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.