1

I am kinda stumped on figuring this out. I want to populate an array with the string values that comes from a for-in loop.

Here's an example.

 let names = ["Anna", "Alex", "Brian", "Jack"]

 for x in names {
     println(x)
 }

The current x value would generate 4 string values (Anna, Alex, Brian, Jack).

However I need some advice in going about getting these four values back into an array. Thank you in advance.

4
  • names is already an array of the 4 strings you want... Or perhaps I misunderstand the question? Commented Jul 6, 2015 at 12:27
  • sorry for being unclear. What i meant was if i wanted to make a new array, let's say namearray2 that consisted of these four names. How would i go about it by using the the values that are generated by the for-in statement? Commented Jul 6, 2015 at 12:29
  • 1
    the easiest way would be without a for loop: let newNames = names Commented Jul 6, 2015 at 12:31
  • 1
    alternatively, if you want to perform some transformation on the strings, you need map i.e. let uppercaseNames = names.map { $0.uppercaseString } creates a new array containing ["ANNA", "ALEX", "BRIAN", "JACK"] Commented Jul 6, 2015 at 12:37

1 Answer 1

2

Whatever is on the right side of a for - in expression must be a SequenceType. Array, as it happens, can be initialised with any SequenceType. So if you're just doing something like this:

var newArray: [String] = []
for value in exoticSequence {
  newArray.append(value)
}

The same thing can be accomplished (faster), by doing this:

let newArray = Array(exoticSequence)

And it doesn't matter what type exoticSequence is: if the for-in loop worked, Array() will work.

However, if you're applying some kind of transformation to your exoticSequence, or you need some kind of side effect, .map() might be the way to go. .map() over any SequenceType can return an array. Again, this is faster, and more clear:

let exoticSequence = [1, 2, 3]

let newArray = exoticSequence.map {
  value -> Int in
  // You can put whatever would have been in your for-in loop here
  print(value)
  // In a way, the return statement will replace the append function
  let whatYouWouldHaveAppended = value * 2
  return whatYouWouldHaveAppended
}

newArray // [2, 4, 6]

And it's equivalent to:

let exoticSequence = [1, 2, 3]

var newArray: [Int] = []
for value in exoticSequence {
  print(value)
  let whatYouWouldHaveAppended = value * 2
  newArray.append(whatYouWouldHaveAppended)
}

newArray // [2, 4, 6]
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.