Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[SR-8779] UnsignedInteger constraint on RandomNumberGenerator is not ideal #51287

Open
Azoy opened this issue Sep 18, 2018 · 3 comments
Open
Labels
bug A deviation from expected or documented behavior. Also: expected but undesirable behavior. standard library Area: Standard library umbrella

Comments

@Azoy
Copy link
Member

Azoy commented Sep 18, 2018

Previous ID SR-8779
Radar None
Original Reporter @Azoy
Type Bug
Additional Detail from JIRA
Votes 0
Component/s Standard Library
Labels Bug
Assignee None
Priority Medium

md5: 7065369b6f42acb03b6e059f6af05a15

Issue Description:

Lack of a better bug title, these extension methods on RandomNumberGenerator:

public func next<T: FixedWidthInteger & UnsignedInteger>() -> T {}

public func next<T: FixedWidthInteger & UnsignedInteger>(upperBound: T) -> T {}

are somewhat difficult to work with. Here is the implementation of randomElement() on Collection:

  public func randomElement<T: RandomNumberGenerator>(
    using generator: inout T
  ) -> Element? {
    guard !isEmpty else { return nil }
    let random = generator.next(upperBound: UInt(count))
    let index = self.index(
      startIndex,
      offsetBy: numericCast(random)
    )
    return self[index]
  }

Granted the numericCast might be unnecessary and you can achieve the same using Int(random), but removing the UnsignedInteger constraint allows for an implementation like so:

  public func randomElement<T: RandomNumberGenerator>(
    using generator: inout T
  ) -> Element? {
    guard !isEmpty else { return nil }
    let random = generator.next(upperBound: count)
    let index = self.index(
      startIndex,
      offsetBy: random
    )
    return self[index]
  }

This is just one example of where removing this constraint is helpful.

@Azoy
Copy link
Member Author

Azoy commented Sep 18, 2018

cc: @stephentyrone

@belkadan
Copy link
Contributor

You're supposed to use Int.random(in: 0...count, using: &generator), not call next directly. See SE-0202 for more details.

@stephentyrone
Copy link
Member

We have considered something like having .next( ) return any FixedWidthInteger, but basically "what Jordan said". Most use cases should be using the methods that take a range.

@swift-ci swift-ci transferred this issue from apple/swift-issues Apr 25, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug A deviation from expected or documented behavior. Also: expected but undesirable behavior. standard library Area: Standard library umbrella
Projects
None yet
Development

No branches or pull requests

3 participants