Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine two Arrays that are optional

Having some trouble combining two arrays that are optional. Not arrays that contain optional items.

let a : [String]? = ["foo"]
let b : [String]? = nil

or

let a : [String]? = nil
let b : [String]? = nil

or

let a : [String]? = ["foo"]
let b : [String]? = ["bar"]

This obviously doesn't work because the arrays are optional

let combinedArrays : [String]? = a + b

Is there a more concise way than the traditional if let approach using functional or some other cleaner method to combine arrays a and b?

Update: The above example is contrived but below is a more real world example of what I was attempting to do:

func pinToAllSidesOfSuperView() -> [NSLayoutConstraint]?
{
    let horizontalConstraints : [NSLayoutConstraint]? = pinViewToLefAndRight()
    let verticalConstraints : [NSLayoutConstraint]? = pinViewToTopAndBottom()
    return horizontalConstraints + verticalConstraints
}

It would be nice to return an optional return value vs an empty array so the caller of the method can still use the optional features (i.e. if let , guard etc) vs the simple check if Array.isEmpty.

like image 899
slim Avatar asked Nov 28 '22 10:11

slim


1 Answers

I would do it like this:

func +<T>(lhs: Array<T>?, rhs: Array<T>?) -> Array<T>? {
    switch (lhs, rhs) {

    case (nil, nil):
        return nil

    case (nil, _):
        return rhs

    case (_, nil):
        return lhs

    default:
        return lhs! + rhs!

    }
}

let foo: [Int]? = nil
let bar: [Int]? = [1]

foo + foo   // -> nil
foo + bar   // -> [1]
bar + foo   // -> [1]
bar + bar   // -> [1, 1]
like image 75
0x416e746f6e Avatar answered Dec 20 '22 10:12

0x416e746f6e