Swift default argument and ignore argument in protocol method / function

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 } } 
+5
source share
1 answer

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:

 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 :

 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 :

 class OfflineGame : Game { func modeName(_: Int) -> ModeName { //Some code } } 
0
source

Source: https://habr.com/ru/post/1210981/


All Articles