Swiftで行こう!-Protocol(型として使う)
protocolです。
protocol RandomNumberGenerator {
func random() -> Double
}
classを作ります。
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 Diceを作ります。このとき
let generator : RandomNumberGenerator
と、変数generatorの型を指定しています。実際のインスタンスを作る場合はplotocol RandomNumberGeneratorに適合しているclassを当てていきます。
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
}
}
ということで、generatorにはRandomNumberGeneratorに適合しているLinearCongruentialGeneratorを使います。
var d6 = Dice(sides: 6, generator: LinearCongruentialGenerator())
for _ in 1...5 {
print("Random dice roll is \(d6.roll())")
Random dice roll is 3 (無作為にさいころを転がして、3です)と表示されます。
この記事が気に入ったらサポートをしてみませんか?