-2

I have an array:

var numberArray = [1,2,3]

I want to convert this into a string and put it into a label text:

label.text = "123"

I've already tried for loops / other things online. Thanks :)

Jawad Ali
  • 13,556
  • 3
  • 32
  • 49

1 Answers1

4

You can simply do this using higher order functions Map and Reduce

label.text = numberArray.map{ String($0) }.reduce("", +)

Or you can use joined() as well

label.text = numberArray.map{String($0)}.joined()

You can also use map this way

label.text = numberArray.map(String.init).joined()
Jawad Ali
  • 13,556
  • 3
  • 32
  • 49
  • I did try map before but wasn't using reduce and obviously was doing it wrong. Cheers! –  May 16 '20 at 15:15
  • 2
    Joined is definitely the better option. It doesn't matter for these small sizes, but reduce has quadratic time complexity, because it makes a new string on every step of the computation. That would be a big deal for larger datasets – Alexander May 16 '20 at 15:31
  • Yes @Alexander-ReinstateMonica you are perfectly right – Jawad Ali May 16 '20 at 15:41