0

I have a Range with float numbers. I need to get the first and the last elements of the range. With Range everything works fine. However when I try to get values from float range I get error "Ambiguous reference to member 'first'". How do I get values from float range?

I tried casting, unwrapping - same error. Looked at posts with similar problem but nothing seems to work.

let range: Range = 1.0..<3.22

let first: CGFloat = range.first (!)(Ambiguous reference to member 'first')

I expect to get the first item from the range, instead I get an error.

Swifless
  • 87
  • 10

1 Answers1

4

first is a method of the Collection protocol (and last a method of BidirectionalCollection). A Range is a (bidirectional) collection only if the underlying element type is an integer type, or any other type that conforms to the Strideable protocol with an integer stride. Example:

let intRange = 1..<10
print(intRange.first!) // 1
print(intRange.last!)  // 9

A range of floating point numbers is not a collection, so there is no first or last method. But you can retrieve the lower/upper bound:

let range: Range<CGFloat> = 1.0..<3.22
print(range.lowerBound)  // 1.0
print(range.upperBound)  // 3.22
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • Worth to note that no floating point type ranges can be `Collection`s, because to do so you need to be able to sequence numbers between lower and upper bound. You can't do this with floating point numbers at all. You can't have `next` number for any `CGFloat`, and you can't tell which number in the range would be `nth`. – user28434'mstep Jul 30 '19 at 09:25
  • 1
    @user28434: In fact you could: The binary floating point types can only represent finitely many values, and actually there are `nextUp`/`nextDown` methods. But it would be of no practical usage. – Martin R Jul 30 '19 at 09:27