1

I am trying to convert this code block to work in swift 3.

let grainSize = CGFloat(0.01)
    let min = CGFloat(-3)
    let max = CGFloat(3)
    let range = Range<Int>(start: Int(min/grainSize), end: Int(max/grainSize))

The issue I am facing is with the Range - I have tried to look through apple docs, but don't really know what I'm even looking for. The issue that it reports is that it says that Cannot convert value of type 'Int' to expected argument type 'NSRange' (aka '_NSRange')

Can anyone help help me understand what is going on here and where/what documentation I can read to make sense of this?

stktrc
  • 1,599
  • 18
  • 30

2 Answers2

1

Try this in Swift 3, it will work. There are no init(start: end:) method in Range. That is the reason for this error.

let grainSize = CGFloat(0.01)
let min = CGFloat(-3)
let max = CGFloat(3)
let range = Range<Int>(uncheckedBounds: (lower: Int(min/grainSize), upper: Int(max/grainSize)))

This creates following range:

-300..<300

adev
  • 2,052
  • 1
  • 21
  • 33
  • By the way, I dont get the error mentioned in question. For me it clearly says, there are no initializer of type `(start:Int, end:Int)` in `Range`. Most probably the error mentioned occurred at some other line of code which is not shared in question. But in any case, the above answer should fix the error since now you have a valid `range`. – adev Aug 16 '17 at 07:24
  • In case you want to convert to `NSRange`, you can use `NSRange(range)` to convert `Range` – adev Aug 16 '17 at 07:26
1

You can get more powerful Countable range with more simple syntax:

let range = (Int(min/grainSize)..<Int(max/grainSize))

It returns CountableRange, not just Range, so you can access to RandomAccessCollection methods, for example.

And if you want to get only Range value you can cast it like this:

let range = Range(Int(min/grainSize)..<Int(max/grainSize))

Also helpful post about ranges in swift 3.

pacification
  • 5,838
  • 4
  • 29
  • 51