Brandon Bradley
Brandon Bradley

Reputation: 3378

How would you create a multidimensional array with n dimensions in Swift?

For instance, asume

var hierarchicalFileSystem: [[String]] = []

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.

Am I missing something here?

Upvotes: 0

Views: 217

Answers (4)

Moriya
Moriya

Reputation: 7906

What you can perhaps do is create an array with AnyObject and add new depths as you need it

var fileSystem: [AnyObject] = []

This would be a very bad way of representing a file system however and you should really go with some kind of tree structure like

struct Node {
    children: [Node]?
    parent: Node?
    name: String 
}

Upvotes: 2

user3441734
user3441734

Reputation: 17534

you can have as much dimensional array as you want. is it a good idea? i don't think ...

var threeDArray: Array<Array<Array<String>>> = []
let oneDArray = ["1","2","3"]
let twoDArray1: Array<Array<String>> = [oneDArray, oneDArray, oneDArray, oneDArray, oneDArray]
let twoDArray2 = twoDArray1 + [["4","5","6"],["7","8","9"]]
threeDArray.append(twoDArray1)
threeDArray.append(twoDArray2)
let arr = [threeDArray,threeDArray,threeDArray]

print(arr.dynamicType) // Array<Array<Array<Array<String>>>>

Upvotes: -1

zuziaka
zuziaka

Reputation: 575

Swift is type-safe language. You have to declare type of your variable, or set it to AnyObject, but please don't. So, answering your question: yes it's possible:

var array: [AnyObject] = [[[1,2,3], [1,2,3]], [[1,2,3],[1,2,3]]]

But this is awful. Try to figure out better representation for your problem. Maybe custom structures.

Upvotes: 0

nhgrif
nhgrif

Reputation: 62052

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

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]()

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).

Upvotes: 2

Related Questions