Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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]
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]
@yagudaev
Copy link

yagudaev commented Aug 17, 2014

Looks great, but sadly gives a syntax error on line 4, 8 and 9. Is there anything else that might be missing?

@yagudaev
Copy link

yagudaev commented Aug 17, 2014

Seems like the syntax of swift has changed. For ArrayTypes now need to be surrounded by brackets so T [] -> [T]. Can you update the gist to reflect that? It is now the second entry on google.

@muellersergej
Copy link

muellersergej commented Aug 23, 2014

A rather simpler way would be to use a closure on the Range. But it will only work on Integer ranges.

let array = (1...4).map { $0 }

@andy318
Copy link

andy318 commented Nov 24, 2014

This works too (in Xcode 6.1) -

var z = [Int](1...10)

@kakubei
Copy link

kakubei commented Mar 5, 2015

@andy318. Great stuff, thanks a lot! Works great.

@SimplGy
Copy link

SimplGy commented Aug 19, 2016

What does this provide above Array(1...42)?

@eonist
Copy link

eonist commented Jan 12, 2017

Swift 3?

@keisei1092
Copy link

keisei1092 commented Feb 7, 2017

👍

@RomanVolkov
Copy link

RomanVolkov commented Mar 14, 2017

@eonist
(1...40).map { String($0) }
Swift 3

@eonist
Copy link

eonist commented Mar 16, 2017

Meta: I googled this again. And found my self asking the same question. :P

@Gerst20051
Copy link

Gerst20051 commented Apr 12, 2017

Thanks @RomanVolkov was just about to post that same thing.

@noamtamim
Copy link

noamtamim commented May 7, 2017

I found this to be the best option in Swift 3:

Array(0...3)    // [0,1,2,3]
Array(0..<3)    // [0,1,2]

@honghaoz
Copy link

honghaoz commented Sep 1, 2020

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