-1

I’m new to this and maybe this is a very bad approach, so let me know please. I want to create an array of integers by a function that use variadic integers as an input and return the square of those integers in an array. But at the end I forced to initialize the return array by a bogus integer which I ended with a [0]. How to eliminate this 0 in my return array and/or what is the correct solution to this problem? Thanks.

func square(numbers: Int...) -> [Int] {
    var x = 0
    var y = [0]
    var counter = 0
    for i in numbers {
        repeat {
            x = i*i
            counter+=1
            y.append(x)
        } while counter == numbers.count
    }
    return y
}
Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
Bezi
  • 57
  • 1
  • 7

1 Answers1

1

You can simply use map(_:) on numbers to return the squares, i.e.

func square(numbers: Int...) -> [Int] {
    numbers.map { $0 * $0 }
}

There is no need to write the boilerplate code for what Swift has already provided.

PGDev
  • 23,751
  • 6
  • 34
  • 88