0

Is it possible to save an array of names within an array? For example, Lets say we have 2 car companies, Toyota and Honda. And lets say we want to create an array within the car company array of the cars they make. For example...

var ArrayWithinArray = ["Toyota, "SIENNA", "CAMRY"", "Honda, "Odyssey", "Civic""]

How would i do this using swift?

4
  • An Array is an object. An Array is an object which contains pointers to other objects. Think about it. Commented May 15, 2015 at 13:05
  • What do you mean? How can i a list of data within a list? Commented May 15, 2015 at 13:07
  • I believe Dictionary [String : AnyObject] will be best here - company as a key and array of cars as value. Commented May 15, 2015 at 13:08
  • @HotLicks <pedantry>In Swift, an array is a value which contains other values.</pedantry> Those values may or may not be references (pointers). Commented May 15, 2015 at 13:17

1 Answer 1

1

In such situation, you can create an dictionary of arrays like this:

var listData = [
"Toyota": ["SIENNA", "CAMRY"],
"Honda": ["Odyssey", "Civic"]
]

To access a particular model, ("SIENNA" here)

let model = listData["Toyota"]?.first ?? "Car not found"

model will contain SIENNA

And if you want to iterate over all models

for model in listData["Toyota"] ?? [] {
    println(model)
}
Sign up to request clarification or add additional context in comments.

6 Comments

That sure looks more like a dictionary of arrays to me.
How would i get the sienna value to print? println(self.listData[?])
I get an error that says. "Expression resolves to an unused l-value"
@LeonardoSavioDabus added your comment as answer, thanks for it
To add another model listData["Toyota"]?.append("Prius"). To add a whole new line of cars: listData["Ford"] = ["Taurus", "F-150"].
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.