Advanced Swift 3 - Part 9: Ranges | Ray Wenderlich

In this video you will learn about the Swift range types in detail and shows how they can be extended without repeating yourself.


This is a companion discussion topic for the original entry at https://www.raywenderlich.com/3810-advanced-swift-3/lessons/9

@rayfix Hey Ray, great vid as always.

Just wondering about why we need to use IndexDistance and numericCast as opposed to just getting the Int result. (Attempt3).

Thanks

Hi. Sorry for the late reply. I have been geeking out on WWDC.

So. index(_:offsetBy:) takes an IndexDistance type. You can’t just pass an Int in there. IndexDistance is a SignedInteger and Index is an Int. That is a convenient way to convert between the types. Actually I am not aware of any other way to do it. Do you know of one?

Attempt 3 can be more concise.

extension RandomAccessCollection where Index == Int {
  var random: Iterator.Element {
    precondition(!isEmpty)
    let index: Int = numericCast(startIndex + (endIndex-startIndex).randomUniform)
    return self[index]
  }
}