Advanced Swift: Generics and Protocols · Associated Type Constraints |

This is a companion discussion topic for the original entry at

Hi Ray,
Thanks for this awesome material, it puts me up to speed on the latest topics of the Swift language.

I want to ask, why are you using the following code on the default implantation of the sample method?:

extension Distribution {
   func sample<G: RandomNumberGenerator>(count: Int, using generator: inout G) -> [Value] {
      var g = SystemRandomNumberGenerator() // <--- Specifically this line?
      return (1...count).map { _ in sample(using: &g) }


shouldn’t it be something like this?

func sample<G: RandomNumberGenerator>(using generator: inout G) -> Int {
     return Value.random(in: range, using: &generator)

where we use the parameter of generic type G, otherwise we are hardcoding the RandomNumberGenerator protocol to SystemRandomNumberGenerator or perhaps I missed something?

Thanks again and best regards.
Iván M.

Oops. Thanks for your note. I will need to fix this. Yes, you are right! Sorry about that. The whole purpose of adding a parameter is so that you can customize it. The sample() methods that don’t take a generator are not declared as part of the formal protocol because you never want those to be overridden. It is a way to guarantee they are used with the SystemRandomNumberGenerator.

Absolutely, that’s my understanding.


Loved the material man, please consider this just friendly feedback, topic is already complex on its own, adding probability theory to the mix was a big distraction for me.