2

I am new to iOS development, and for some reason I can't figure out how to do this even though I realize it has to be simple. I want to create a collection with 2 string values. For instance:

var firstName = "Bob"
var lastName = "Smith"

So the first index would contain ("Bob", "Smith") and so one for each first and last name I want to add to the collection. What object do I use? I tried a dictionary but it seems you have to add your values to that up front, and I need to add my later on programmatically.

2
  • You can modify a dictionary at any time if it's declared as a var: var dict = [:] dict["x"] = 4 Commented Jul 9, 2014 at 22:04
  • 4
    You are asking the questions and didn't read Apple Swift Book. There it is. Commented Jul 9, 2014 at 22:06

3 Answers 3

4

You could use a dictionary but I'd create a Person struct that contains a firstName and a lastName and put those into an array.

struct Person {
    var firstName: String
    var lastName: String
}

var firstName = "Bob"
var lastName = "Smith"

var array = [Person(firstName: firstName, lastName: lastName)]

It also has the benefit of being able to access the parts using .firstName and .lastName

array[0].firstName

As opposed to a dictionary that that requires a string

array[0]["firstName"]
Sign up to request clarification or add additional context in comments.

Comments

2

To create an array with only string you use

var shoppingList: [String] = ["Eggs", "Milk"]

And to add to the end of the array (push) you use

shoppingList.append("Bread")

Comments

1

The struct way is preferred, but if you want to do something more similar to the initial request you could do an array of tuples

Comments

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.