0

I'm learning algorithms and data structures, I'm on a question that returns a array and squares it. sortedSquares is the variable name.

Recently, I looked up what it meant and I got a result that said that it was just a array that repeats zeros, but it seems like I could just use sortedSquares = [] with similar effect.

AlgoExpert is the platform that I'm using, so I cant upload all the code because of copyright stuff.

P.S. -- I'm 2 weeks into learning swift and any help would be great...thanks.

var sortedSquares = array(repeating: 0, from: array.count, by: 1)
3
  • With var sortedSquares = [], then sortedSquares is an Empty array... Print Array(repeating: 0...). Depending on array.count it could also be an empty array... Commented Nov 4, 2022 at 20:59
  • Just to be sure, are you new to programming? Or you know programming, but are just picking up Swift and Data Structure at the same time? Commented Nov 4, 2022 at 21:08
  • I’m almost certain that array(repeating: 0, from: array.count, by: 1) isn’t the actual code. Please show the actual, code. (or that’s really it, it’s using a function you haven’t shown us, which you would need to do) Commented Nov 5, 2022 at 3:32

1 Answer 1

1

Sometimes you need an empty array (no elements) and other times you need an array pre-filled with a certain number of placeholder values. Using Array.init(repeating:0) will populate your array with zeros, which is not the same thing as an empty array.

var ints: [Int]

// after this line, print(array.count) disaplays 0, and `array.isEmpty` evaluates to true
ints = [] 

// after this line, print(array.count) returns 10, and print(array) 
// prints an array of 10 zeros. Also `array.isEmpty` evaluates to false.    
ints = Array(repeating: 0, count: 10) 
Sign up to request clarification or add additional context in comments.

1 Comment

If this answers your question you should accept it. That’s a strong norm on Stack Overflow. Up-votes are entirely optional, but you are expected to accept the first answer that solves our problem (or the best answer if a later answer is substantially better.)

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.