Meta question: I am kinda lost on how exactly one uses Documentation. Currently it shows me the docs for 5.10 beta
. I am on 5.9.2
and I would like to check the docs for that.
For the actual question, I am not sure if this is because of the version mismatch, but I am trying to follow Documentation. The code shown there (complete example as follows) does not work. I get the following error
error: protocol 'Delegate' cannot be nested inside another declaration
But the docs claim
Protocols can be nested inside of type declarations like structures and classes, as long as the outer declaration isn’t generic.
This is the example from the link above. I just added the RandomNumberGenerator
and LinearCongruentialGenerator
implementation for completeness. I do not think I did a naive copy paste / typo here.
protocol RandomNumberGenerator {
func random() -> Double
}
class LinearCongruentialGenerator: RandomNumberGenerator {
var lastRandom = 42.0
let m = 139968.0
let a = 3877.0
let c = 29573.0
func random() -> Double {
lastRandom = ((lastRandom * a + c)
.truncatingRemainder(dividingBy:m))
return lastRandom / m
}
}
class DiceGame {
let sides: Int
let generator = LinearCongruentialGenerator()
weak var delegate: Delegate?
init(sides: Int) {
self.sides = sides
}
func roll() -> Int {
return Int(generator.random() * Double(sides)) + 1
}
func play(rounds: Int) {
delegate?.gameDidStart(self)
for round in 1...rounds {
let player1 = roll()
let player2 = roll()
if player1 == player2 {
delegate?.game(self, didEndRound: round, winner: nil)
} else if player1 > player2 {
delegate?.game(self, didEndRound: round, winner: 1)
} else {
delegate?.game(self, didEndRound: round, winner: 2)
}
}
delegate?.gameDidEnd(self)
}
protocol Delegate: AnyObject {
func gameDidStart(_ game: DiceGame)
func game(_ game: DiceGame, didEndRound round: Int, winner: Int?)
func gameDidEnd(_ game: DiceGame)
}
}
The "fix" seems to just move Delegate
outside the DiceGame
class, but still, curious to know if this is an error due to version mismatch, if so, how exactly do I get the docs for a version I want (5.9.2
)?