简体   繁体   English

使用不同的数据类型在swift中创建多维数组

[英]Create multidimentional array in swift with different datatypes

this is my first question here so forgive me if it is not very clear. 这是我的第一个问题,请原谅我,如果不是很清楚的话。

I am trying to create an array in swift that will store either arrays of arrays or an integer number. 我试图在swift中创建一个数组,它将存储数组数组或整数。 The array is supposed to be a simple representation of the data I will be using which is basically a tree kind of data structure like so... 该数组应该是我将使用的数据的简单表示,它基本上是一种树类数据结构,如此......

Array = [ [ [ [2, 3] ] , [ 1, 4 ] , [ 2 ] ], [ 2 ] , [ [2, 5], [6, 1] ] , 3 ] 数组= [[ [ [2,3] ][ 1,4 ][ 2 ] ], [ 2 ][ [2,5],[6,1] ] ,3]

In overall the arrays are the branches and the integers are the leaves 总的来说,数组是分支,整数是叶子

I've tried declaring them as optionals like so 我已经尝试将它们声明为可选项

var test2 = [[[Int]?]?]()

Or using typedef's but I still can't get it to work. 或者使用typedef,但我仍然无法使用它。

Also, it should be possible to add new leaves to any of the arrays 此外,应该可以向任何阵列添加新叶

Here is a solution based on enum , first declare the enum : 这是一个基于enum的解决方案,首先声明enum

enum Node
{
    case leaf(Int)
    case branch([Node])
}

You can now write things such as: 您现在可以编写以下内容:

let x = Node.leaf(42)
let y = Node.branch([Node.leaf(42), Node.leaf(24)])

However this is going to become laborious very quickly. 然而,这将很快变得费力。 Fortunately Swift allows conversions from literals, so we add: 幸运的是,Swift允许从文字转换,所以我们添加:

extension Node : ExpressibleByIntegerLiteral
{
    init(integerLiteral value: Int)
    {
        self = .leaf(value)
    }
}

extension Node : ExpressibleByArrayLiteral
{
    init(arrayLiteral elements: Node...)
    {
        self = .branch(elements)
    }
}

And with those added we can now write the above two let statements as: 通过添加这些,我们现在可以将以上两个let语句编写为:

let x : Node = 42
let y : Node = [42, 24]

which is nicer. 哪个更好。 However if we print(y) we get: 但是,如果我们print(y)我们得到:

branch([Node.leaf(42), Node.leaf(24)])

If you wish to pretty print that you can add: 如果您希望打印漂亮,可以添加:

extension Node : CustomStringConvertible
{
    var description : String
    {
        switch self
        {
            case .leaf(let value):
                    return value.description
            case .branch(let branches):
                    return branches.description
        }
    }
}

And now print(y) gives you: 现在print(y)给你:

[42, 24]

Finally your example: 最后你的例子:

let w : Node = [[[[2, 3]], [1, 4], [2]], [2], [[2, 5], [6, 1]], 3]

which prints as: 打印为:

[[[[2, 3]], [1, 4], [2]], [2], [[2, 5], [6, 1]], 3]

You'll want to complete the enum type, with predicates such as isLeaf etc., but that is the basic idea. 你需要使用诸如isLeaf类的谓词来完成enum类型,但这是基本的想法。

HTH HTH

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

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