1

I have an array of strings, which i need to convert into single String with multi line

 var array = ["A","B","C","D","E"]
 var multiLineString = //convert array to a string
 println("\(multiLineString)")

The output should be:

  A 
  B 
  C 
  D 
  E 
Kirsteins
  • 27,065
  • 8
  • 76
  • 78
iPhone Guy
  • 1,285
  • 3
  • 23
  • 34
  • possible duplicate of [Concatenate String in Swift](http://stackoverflow.com/questions/26583300/concatenate-string-in-swift) – Antonio Oct 27 '14 at 09:42

3 Answers3

3

That should be something like:

var array = ["A","B","C","D","E"]
var multiLineString = join("\n", array)
println("\(multiLineString)")

Note that the console does not print this on multiple lines.

UPDATE: To get the height of the label to display this string:

let label = UILabel()
label.text = multiLineString
label.numberOfLines = 0
label.lineBreakMode = NSLineBreakMode.ByWordWrapping
label.sizeToFit()
println("Height: \(label.frame.height)")
Tom
  • 874
  • 7
  • 13
  • i need to get the total height of a string. so that i can display string in multi lines in a cell. Does 'multiLineString' gives the correct height? – iPhone Guy Oct 27 '14 at 09:37
  • @iPhoneGuy see my updated answer how to get the correct height of a label displaying this string. – Tom Oct 27 '14 at 09:48
1

Try join:

var array = ["A","B","C","D","E"]
var multiLineString = join("\n", array)
println("\(multiLineString)")
Kirsteins
  • 27,065
  • 8
  • 76
  • 78
  • i need to get the total height of a string. so that i can display string in multi lines in a cell. Does 'multiLineString' gives the correct height? – iPhone Guy Oct 27 '14 at 09:38
  • @iPhoneGuy: You seem to mix different problems here. A *string* is just a collection of characters, unrelated to the visual represention. The *height* depends on other parameters, such as the selected *font*. Perhaps this http://stackoverflow.com/questions/7174007/how-to-calculate-uilabel-height-dynamically (and the related questions) is what you are looking for. – Martin R Oct 27 '14 at 09:46
  • Correct @MartinR. However, I updated my answer above to display how you can get the height of a label displaying the string. – Tom Oct 27 '14 at 09:47
1

Since Swift 2.0 this would produce the error:

Cannot invoke join with an argument list of type (String, [String])

Use this instead:

array.joinWithSeparator("\n")

kl.woon
  • 2,036
  • 1
  • 18
  • 10