1

I have an array with 10 objects all of the same self-created class.

let myArray = [CustomObject(), CustomObject(), CustomObject(), CustomObject(), CustomObject(), CustomObject(), CustomObject(), CustomObject(), CustomObject(), CustomObject()]

I wonder if there is a shortcut for creating such an array like in Python where I would do something like

myArray = [CustomObject() for _ in range(10)]

I have seen these solutions: StackOverflow-Link but they don't seem to work with not built-in classes.

let myArray2 = (0...9).map{CustomObject()}

says "Type of expression is amiguous without more context"

2 Answers 2

3

Try this

let myArray = [CustomObject](repeating: CustomObject(), count: 10)

By using Array.init(repeating:) will invoke the CustomObject initialize only one time, and then insert that object into the array multiple times.

If you want to use Array.init(repeating:) with the different object I found one thread and extension https://forums.swift.org/t/support-repeating-initializers-with-closures-not-just-values/14666/5

If you want to use the map and for different object.

let myArray2 = (0...9).map { (_) -> CustomObject in
    CustomObject()
}
Sign up to request clarification or add additional context in comments.

4 Comments

Your solution using Array.init(repeating:) will invoke the CustomObject initializer only once, and then insert that object into the array multiple times. That is likely not what the OP wants or expects.
No I need 10 different objects. So the map solution would be what I need?
@DuncanC yes you are right. Using Array.init(repeating:) object initializer only one time. so a map is a good solution in my view.
If you want to use Array.init(repeating:) with the different object I found one thread and extension forums.swift.org/t/…
0

Prefixing an AnyIterator that produces infinite Voids is my recommendation. Then you don’t need to disregard a closure parameter, allowing you to use the initializer directly as a named closure.

AnyIterator { } .prefix(10).map(CustomObject.init)

Comments

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.