如何组合两个可选的数组

sli*_*lim 4 arrays functional-programming ios swift

在组合两个可选的数组时遇到一些麻烦.不包含可选项的数组.

let a : [String]? = ["foo"]
let b : [String]? = nil
Run Code Online (Sandbox Code Playgroud)

要么

let a : [String]? = nil
let b : [String]? = nil
Run Code Online (Sandbox Code Playgroud)

要么

let a : [String]? = ["foo"]
let b : [String]? = ["bar"]
Run Code Online (Sandbox Code Playgroud)

这显然不起作用,因为数组是可选的

let combinedArrays : [String]? = a + b
Run Code Online (Sandbox Code Playgroud)

有没有比传统if let方法更简洁的方法,使用功能或其他更清洁的方法来组合数组a和b?

更新: 上面的例子是设计的,但下面是我试图做的更真实的例子:

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

这将是很好返回一个可选的返回值VS空数组因此该方法的调用者仍然可以使用可选功能(即if let,guard等)与简单的检查,如果Array.isEmpty.

Luk*_*kas 9

我不确定这是否足够整洁但无论如何它会给出组合的字符串数组

var combined = (a ?? []) + (b ?? [])
Run Code Online (Sandbox Code Playgroud)

许多其他选项之一是使其成为计算属性,如果组合数组为空,则返回nil

var combined:[String]?{
    let c = (a ?? []) + (b ?? [])
    return c.isEmpty ? nil : c
} 
Run Code Online (Sandbox Code Playgroud)


cou*_*elk 7

我会这样做:

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]
Run Code Online (Sandbox Code Playgroud)


Ben*_*Ben 6

对于更实用的方法,您可以使用compactMapandflatMap来实现这一点。

类似于以下内容:

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

let combined = [a, b]   // create array with both optional arrays
    .compactMap({ $0 }) // remove optional from it
    .flatMap({ $0 })    // merge elements into a final array

Run Code Online (Sandbox Code Playgroud)

希望能帮助到你!