Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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