Last active
July 4, 2023 13:00
-
-
Save nubbel/d5a3639bea96ad568cf2 to your computer and use it in GitHub Desktop.
This file contains 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
protocol ArrayRepresentable { | |
typealias ArrayType | |
func toArray() -> ArrayType[] | |
} | |
extension Range : ArrayRepresentable { | |
func toArray() -> T[] { | |
return T[](self) | |
} | |
} | |
(1..5).toArray() // => [1, 2, 3, 4] | |
(-2.0..2.0).toArray() // => [-2.0, -1.0, 0.0, 1.0] | |
This file contains 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
func toArray<S : Sequence>(seq: S) -> Array<S.GeneratorType.Element> { | |
return Array<S.GeneratorType.Element>(seq) | |
} | |
toArray(1..5) // => [1, 2, 3, 4] | |
toArray(-2.0..2.0) // => [-2.0, -1.0, 0.0, 1.0] |
Meta: I googled this again. And found my self asking the same question. :P
Thanks @RomanVolkov was just about to post that same thing.
I found this to be the best option in Swift 3:
Array(0...3) // [0,1,2,3]
Array(0..<3) // [0,1,2]
import Foundation
public extension Range where Bound: Strideable, Bound.Stride: SignedInteger {
/// Convert to an array.
func asArray() -> [Bound] {
Array(self)
}
}
public extension ClosedRange where Bound: Strideable, Bound.Stride: SignedInteger {
/// Convert to an array.
func asArray() -> [Bound] {
Array(self)
}
}
public extension Sequence {
/// Convert to an array.
func asArray() -> [Iterator.Element] {
Array(self)
}
}
(1 ..< 4).asArray() // [1, 2, 3]
(1 ... 4).asArray() // [1, 2, 3, 4]
zip([1, 2, 3], ["a", "b", "c"]).asArray() // [(1, "a"), (2, "b"), (3, "c")]
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@eonist
(1...40).map { String($0) }
Swift 3