Skip to content

Instantly share code, notes, and snippets.

@SaltySpaghetti
Created October 24, 2022 14:02
Show Gist options
  • Save SaltySpaghetti/db541f74b80c1ea00065d54d23ed531f to your computer and use it in GitHub Desktop.
Save SaltySpaghetti/db541f74b80c1ea00065d54d23ed531f to your computer and use it in GitHub Desktop.
Swift porting of Dart List.generate method
extension Array<Any> {
static func generate<T>(_ length: Int, _ generator: (_ index: Int) -> T) -> [T] {
return (0...length).map { (index) in generator(index) }
}
}
//Usage
Array.generate(5, { index in return Int.random(in: 0...5) }) //[3, 2, 4, 1, 5]
Array.generate(5, { index in return "Element \(index)" }) //["Element 0", "Element 1", ...]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment