7

I have an array of strings for one variable, and a string as another variable. I'd like to append all of the strings in the collection to the single string.

So for example I have:

 var s = String()

   //have the CSV writer create all the columns needed as an array of strings
   let arrayOfStrings: [String] = csvReport.map{GenerateRow($0)}

// now that we have all the strings, append each one 
        arrayOfStrings.map(s.stringByAppendingString({$0}))

the line above fails. I've tried every combination I can think of, but at the end of the day, I can't get it unless I just create a for loop to iterate through the entire collection, arrayOfStrings, and add it one by one. I feel like I can achieve this the same way using map or some other function.

Any help?

Thanks!

1
  • my answer was deleted with explanation "Code-only answers are considered low-quality and are liable to be deleted". you can use arrayOfStrings.reduce(s, combine: +). Commented Nov 28, 2015 at 21:24

3 Answers 3

19

You can use joined(separator:):

let stringArray = ["Hello", "World"]
let sentence = stringArray.joined(separator: " ")  // "Hello World"
Sign up to request clarification or add additional context in comments.

Comments

7

You could convert your array to string using joinWithSeparator(String) here is an example

var array = ["1", "2", "3"]
let stringRepresentation = array.joinWithSeparator("-") // "1-2-3"

source: [ How do I convert a Swift Array to a String? ]

Comments

2

There are at least two options here. The most semantic choice is likely joinWithSeparator on the [String] object. This concatenates every string in the array, placing the separator provided as a parameter between each string.

 let result = ["a", "b", "c", "d"].joinWithSeparator("")

An alternative is to use a functional reduce and the + function operator which concatenates strings. This may be preferred if you want to do additional logic as part of the combine. Both example code produce the same result.

 let result = ["a", "b", "c", "d"].reduce("", combine: +)

It's also worth noting the second options is transferrable to any type that can be added, whereas the first only works with a sequence of strings, as it is defined on a protocol extension of SequenceType where Generator.Element == String.

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.