Kyle Decot
Kyle Decot

Reputation: 20835

Create a typed array w/ N items in it using Swift

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?

Upvotes: 4

Views: 1115

Answers (4)

Peter Kreinz
Peter Kreinz

Reputation: 8676

Swift 4.2

struct Cube {
    let id:Int
}

...    

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

Upvotes: 0

jrc
jrc

Reputation: 21939

In Swift 2, this is

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

Upvotes: 2

Airspeed Velocity
Airspeed Velocity

Reputation: 40973

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.

Upvotes: 3

David Berry
David Berry

Reputation: 41246

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

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

Upvotes: 0

Related Questions