This is a companion discussion topic for the original entry at https://www.raywenderlich.com/1940187-advanced-swift-generics-and-protocols/lessons/6
This is a companion discussion topic for the original entry at https://www.raywenderlich.com/1940187-advanced-swift-generics-and-protocols/lessons/6
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鈥檛 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鈥檛 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鈥檚 my understanding.
Thanks!
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.