如何在Swift中创建n个维度的多维数组? [英] How would you create a multidimensional array with n dimensions in Swift?

查看:72
本文介绍了如何在Swift中创建n个维度的多维数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,假设

var hierarchicalFileSystem: [[String]] = []

这允许一个文件夹支持一层文件夹,但是似乎没有办法像上面的那样在Swift中创建数组,但是

This allows one to support one layer of folders, but there appears to be no way to create an array in Swift like the one above but with an undefined number of nested String arrays.

我在这里缺少什么吗?

推荐答案

由一个数组组成的数组(代表数组的数组...)对表示文件系统没有多大意义。

An array of arrays (of arrays of arrays...) of strings doesn't really make much sense to represent a file system.

我要做什么d而是建议使一个类或结构代表文件系统中的对象。也许是这样的:

What I'd instead recommend is making a class or struct to represent objects in the file system. Perhaps something like this:

struct FileSystemObject {
    let name: String
    let extension: String?
    let isFolder: Bool
    let contents: [FileSystemObject]?
}

像这样的东西让我们很好地表示一个文件系统。

Something like this let's us represent a file system quite nicely.

let fileSystem = [FileSystemObject]()

因此,这里的 fileSystem 变量是 FileSystemObject s的数组,并且它代表根。根目录中的每个对象都有自己的详细信息集(名称,文件扩展名(如果有的话)以及是否是文件夹),如果是文件夹,则其内容为非nil 属性,如果它是一个非空文件夹,则该 contents 个数组由 FileSystemObject 组成包含更多的文件系统对象(当然其中一些是文件夹,它们本身包含内容)。

So, your fileSystem variable here is an array of FileSystemObjects and it represents the root. Each object within the root has its own set of details (its name, its file extension if it has one, and whether or not its a folder), and if it's a folder it has a non-nil contents property, and if it's a non-empty folder, that contents array of FileSystemObjects contains more file system objects (some of which are folders of course, which contain contents themselves).

这篇关于如何在Swift中创建n个维度的多维数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆