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 trialMert Kahraman
12,118 PointsA stored property conforming to a Protocol with a method in it..?
For this given example (on the video: protocols as Types and Apple Documentation):
_Code Begins Here_
protocol RandomNumberGenerator { func random() -> Double }
class LinearCongruentialGenerator: 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:LinearCongruentialGenerator())
_Code Ends Here_
We see that in class Dice there is a stored property called: generator.
generator is of type RandomNumberGenerator which is a Protocol defined at the top.
How come generator can conform to this protocol? To conform with that protocol, shouldn't an object needs to have the random() method?
I understand Classes conforming to a Protocol, but how come this variable be a type of RandomNumberGenerator?
This also means that I haven't understood this video's topic so it's a more general question about Protocols as Types..
I will appreciate your helps, and thanks in advance! Mert
1 Answer
Hemanth C
8,970 PointsProtocols can also be used as the type of a constant, variable, or property, so here its used as type of a constant. Since a protocol is used as a type, the only requirement is when class is instantiated and called, generator property can only take an instance which has adopted RandomNumberGenerator protocol.