日記
お腹すいた
今日書いたコード
https://docs.swift.org/swift-book/LanguageGuide/Protocols.html
protocol Named { var name: String { get } } class Location { var latitude: Double var longitude: Double init(latitude: Double, longitude: Double) { self.latitude = latitude self.longitude = longitude } } class City: Location, Named { var name: String init(name: String, latitude: Double, longitude: Double) { self.name = name super.init(latitude: latitude, longitude: longitude) } } func beginConcert(in location: Location & Named) { print("Hello, \(location.name)!") } let seattle = City(name: "Seattle", latitude: 47.6, longitude: -122.3) beginConcert(in: seattle)
初めて知ったこと
これ読んで腑に落ちたけどViewとViewModelに対してデリゲートパターンを使うような場合はreference semanticsがないと意味ないね.
Use a class-only protocol when the behavior defined by that protocol’s requirements assumes or requires that a conforming type has reference semantics rather than value semantics. https://docs.swift.org/swift-book/LanguageGuide/Protocols.html
Protocol Composition
複数のプロトコルと最大1個のクラスを,&を間において列挙することができる.これはProtocol Compositionと呼ばれている.型を指定できる場所でこう書くと,全てのプロトコルに準拠している,そのクラスのサブクラスを要求できる.
サブクラスというところに引っかかったが,要求するクラスそのものとプロトコルを列挙した場合そこに渡せるインスタンスのクラスはプロトコルに準拠しているはずでプロトコルの列挙が完全に冗長になってしまうのでこれで良さそう.冗長とはいえ間違ってはいないのでCity
のインスタンスを渡すことはできる.
func redundantRequirementTest(in location: City & Named) { print("location.name:", location.name) } redundantRequirementTest(in: seattle)