2

Why is it that:

let i = 1...100
let s = [Int](i)

yields

[1, 2, 3, ..., 100]

but

let i = "a"..."z"
let s = [String](i)

yields

Cannot invoke initializer for type '[String]' with an argument list of type '(ClosedInterval<String>)'

yet

i.contains("b")

yields

true
marco alves
  • 1,707
  • 2
  • 18
  • 28

1 Answers1

3

Int conforms to ForwardIndexType, therefore in

let i = 1...100

... is the operator

public func ...<Pos : ForwardIndexType where Pos : Comparable>(start: Pos, end: Pos) -> Range<Pos>

and the result is a Range<Int>. Ranges are collections and sequences: One can enumerate the elements of the range and create an array from it.

But String and Character do not conform to ForwardIndexType: There is no method to advance from one string or character to the next. Therefore in

let i = "a"..."z"

... is the operator

public func ...<Bound : Comparable>(start: Bound, end: Bound) -> ClosedInterval<Bound>

and the result is a ClosedInterval<String>. You can check if a particular string is contained in that interval, but you can not enumerate its elements.

"a"..."z" represents all strings s for which "a" <= s <= "z" according to the Unicode standard, and not just the 26 lowercase letters from the english alphabet, compare e.g. What does it mean that string and character comparisons in Swift are not locale-sensitive?. For example

let c = i.contains("รค")

yields true.

In Swift 3, the range and interval types have been renamed and reorganized:

"1" ... "100"  // CountableClosedRange<Int>
"a" ... "z"    // ClosedRange<String>

If your intention is to create an array with all characters from "a" to "z" according to their ordering in the Unicode tables then you can enumerate the UTF-32 code units:

let i = UnicodeScalar("a").value ... UnicodeScalar("z").value
let charArray = (i.map { Character(UnicodeScalar($0)) })
// or
let stringArray = (i.map { String(UnicodeScalar($0)) })

The result is

["a", "b", "c", ... , "z"]

as an array of Character or an array of String.

Community
  • 1
  • 1
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382