Created
October 24, 2022 14:02
-
-
Save SaltySpaghetti/db541f74b80c1ea00065d54d23ed531f to your computer and use it in GitHub Desktop.
Swift porting of Dart List.generate method
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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