4

I have a method that I'm using to create an array w/ n of a specific type of object in it:

func many(count: Int) -> [Cube] {
  var cubes: [Cube] = []
  for i in 0...count {
    let cube = CubeFactory.single()
    cubes.append(cube)
  }
  return cubes
}

This works but I'm sure there's a more swift like way to do this. Any one know how this can be refactored?

5
  • func many(count: Int) -> [Cube] { return [Cube](count: count, repeatedValue: Cube.single()) } Commented Jan 29, 2015 at 23:27
  • This is marked as a duplicate, but the referenced question refers to initializing an array with identical values, this question is about initializing it with different values. Commented Jan 29, 2015 at 23:27
  • Although at some point it changed so that it probably is initializing it with a single value now. Need some clarification from the OP about which is actually desired. Commented Jan 29, 2015 at 23:29
  • @David Fair enough. I'll reopen in the mean time. Commented Jan 29, 2015 at 23:30
  • Sorry I didn't clarify but they need to be different objects, just of the same type. Commented Jan 29, 2015 at 23:45

4 Answers 4

3

Does CubeFactory.single() actually do anything other than return the same instance every time?

If it does active stuff, return map(0..<count) { _ in CubeFactory.single() } (or numerous variants) will give you an array of them.

(the _ in really oughtn’t to be necessary, but Swift’s type inference gets a bit flummoxed without it and you’ll get an error about half-open intervals – the other possibility for the overloaded ..< operator – not conforming to SequenceType)

If it’s just inert and every cube is identical, return Array(count: count, repeatedValue: Cube.single()) is all you need.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the information! Do you happen to know if the _ in thing is going to be addressed at some point?
no idea but you’ve reminded me I haven’t filed a radar for it :-)
2

In Swift 2, this is

let array = (0..<30).map { _ in CubeFactory.single() }

Comments

0

Not sure if it's exactly what you're looking for, but you can use:

let array = map(0..<30) { _ in CubeFactory.single() }

2 Comments

You shouldn’t need that SequenceOf – ranges are already sequences.
That's what I thought too, but it didn't seem to work that way. Trying it again it does, so I've updated it.
0

Swift 4.2

struct Cube {
    let id:Int
}

...    

let array = (0..<24).compactMap {
    return Cube(id: $0)
}

1 Comment

Out of curiosity, why the use of compactMap over map, in this example?

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.