-
Notifications
You must be signed in to change notification settings - Fork 0
When
class When<Type, Result>When is a class to imitate an operator which works similar to switch but returns a value.
So it provides a way to map Type to Result
As an instance it could be stored and used as any other instance of any other class but it intended to be used just in place without storing a ref to it.
let result = When<Int, String>(number)
.case(0) {"Invalid number"}
.case(1)
.case(2) {"Number is too low"}
.case(3) {"Number is correct"}
.case(4) {"Numbe is almost correct"}
.default(nil) ?? "Number is too high"Here number is an Int and result is a String.
Despite the fact When is constricted to be used an operator it is a generic type that is why it starts from the capital latter.
When uses one parameter in constructor which determines it's source Type.
This is a value which will be used in cases as a parameter of case's condition block.
When contains two methods:
case and default
To be used as intended default is a method to be called last in a chain of cases.
It provides a value of Result? type and determines the Result type for the When and return type for each case
case returns self for current When instance and is used to create cases chain.
case takes a block check if it is satisfied and result block which returns the Result value in this case.
If When's Type is Equtable case could take not a condition block but just a value of Type to be compared with.
casecould not take a result block. In this case if case is satisfied the very next result block in chain will be executed. If no result block found the value from ```default`` will be returned.