Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS Swift 2.0 Protocols Swift 2.0 Protocols Protocols as Types

DongHyuk Jang
DongHyuk Jang
5,754 Points

For Dice class, we should initialize by (sides: Int, generator: RandomNumberGenerator) but it is strange we use it.

protocol RandomNumberGenerator { func random() -> Double }

class LinearCongrunentialGenerator: RandomNumberGenerator { var lastRandom = 42.0 let m = 129968.0 let a = 3877.0 let c = 29573.0

func random() -> Double {
    lastRandom = ((lastRandom * a + c) % m)
    return lastRandom/m


class Dice { let sides: Int let generator: RandomNumberGenerator init(sides: Int, generator: RandomNumberGenerator) { self.sides = sides self.generator = generator }

func roll() -> Int {
    return Int(generator.random() * Double(sides)) + 1


var d6 = Dice(sides: 6, generator: LinearCongrunentialGenerator())

WHY???????? at last sentence. we didn't put RandomNumberGenerator for initialize of Dice class? "LinearCongrunentialGenerator()"is class not protocol right? Dice class asked "RandomNumberGenerator" for last argument for his initialize. init(sides: Int, generator: RandomNumberGenerator)

Please help me

jonathan chadeyras
jonathan chadeyras
15,015 Points

Hey, as far as I understand your post it is because LinearCongrunentialGenerator conforms to RandomNumberGenerator You can assign to generator any object that conforms to the protocol

If you look again at the video Pasan explains that for the first time with the Fruit/Smoothies exemple. strawberry and chocolateMilk are both conforming to the "Blendable" protocol and both fit in the "ingredients" array of type "Blendable".

Also another example in a previous video called "Modeling behavior with Protocols" tacles the same problem

I hope i was clear and my answer helped you. cya