How to set the protocol function so that it can receive an optional argument or even ignore it?
I have this protocol:
protocol Game { func modeName(forRound: Int) -> ModeName }
Using these 2 special classes:
//Goal: Default forRound should be 0 if none provided class OnlineGame : Game { func modeName(forRound: Int = 0) -> ModeName { //Some code } } //Goal: I don't care about the forRound value here class OfflineGame : Game { func modeName(_ forRound: Int) -> ModeName { //Some code } }
First of all, in the protocol you declare a "method", and the first parameter "method" does not have an external name by default . So, here is the normal code:
protocol
class SomeGame: Game { func modeName(forRound: Int) -> ModeName { // ... } } let game: Game = SomeGame() let modeName = game.modeName(1) // not `game.modeName(forRound: 1)`
In your case OnlineGame if the parameter has a default value, it has an external name automatically , even if this is the first parameter of the method, you can override this behavior with _ as an explicit external name :
OnlineGame
_
class OnlineGame : Game { func modeName(_ forRound: Int = 0) -> ModeName { //Some code } }
In your case, OfflineGame you can ignore the parameter with _ as the internal name :
OfflineGame
class OfflineGame : Game { func modeName(_: Int) -> ModeName { //Some code } }
Source: https://habr.com/ru/post/1210981/More articles:Material card with library Cardslib - androidhow to handle WAI ARIA role = "listbox" - accessibilityHow to install lz4 shared libraries on rpm based machines? - rpmUsing Javascript memory for for loop - javascriptRound Double to the nearest 10 - doubleChromatograph preference setup on protractor tests - javascriptUnable to stop pusher from showing file download - angularjsjquery onclick add background overlay for output - javascriptUnresolved dependency with fabulous flow specs2 0.5a - scala.htaccess RewriteRule also overwrites css, js and images files. how to ignore them? - phpAll Articles