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
.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With