Swiftで行こう!-protocol,class!?
protocolとclass の関係、使い方が少しわかりにくいですね。
でもちょっと考えてみましょう。それはわかりやすさと使い方です。まずはprotocolで定義してからClassを定義したもの。
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 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())
for _ in 1...5 {
print("Random dice roll is \(d6.roll())")
}
classのみを使ったもの。
class LinearCongruentialGenerator {
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 sides: Int
let generator = LinearCongruentialGenerator()
init(sides: Int) {
self.sides = sides
}
func roll() -> Int {
return Int(generator.random() * Double(sides)) + 1
}
}
var d6 = Dice(sides: 6)
for _ in 1...5 {
print("Random dice roll is \(d6.roll())")
}
classを使ったものの方が短くて良さそうでが。
ではprotocolを使うと何が良いかというと、この場合ですとprotocolを使い最初に定義した
func random() -> Double
が最低限 random()の機能が担保できているということです。
classに必要な機能があるかどうかわかりにくいので、protocolで宣言してgeneratorにprotocolに準拠したclassにすることで必要最小限の機能は担保できているので安心して使うことができます。
この記事が気に入ったらサポートをしてみませんか?