本日もSwiftに関する小ネタです🏃♂️
関数でパラメータの設定を任意にする場合、下記のようにデフォルト値を設定することはよくあると思いますが、SwiftのProtocol
はデフォルト値をパラメータに設定することはできません。
class Fish { func printFishName(name: String, location: String = "jp") { print("name: \(name), location: \(location)") } }
こんな感じでエラーになる。
protocol FishProtocol { func printFishName(name: String, location: String = "jp") // Default argument not permitted in a protocol method }
解決策
Protocol
のExtensionにデフォルト値を設定したいメソッドを設定することで実現できます。return printFishName(name: name, location: location)
では、Protocol
に準拠したそれぞれの具象クラスに実装されたメソッドが呼び出されます。
protocol FishProtocol { func printFishName(name: String, location: String) } extension FishProtocol { func printFishName(name: String, location: String = "jp") { return printFishName(name: name, location: location) } }
てな感じで本日も以上となります🍺