How to convert Swift "switch case is ..." block into loop oriented code?

I have a code that looks like this:

class Base {
    func launch(code1: Int, code2: Int) -> Bool { return false }
}

class A: Base {}
class B: Base {}
class C: Base {}

func trynext(obj: Base) -> Base? {
    switch obj {
    case is A: return B()
    case is B: return C()
    default: return nil
    }
}

Basically, I have many (e.g. 20) subclasses of a common base class, and I need to go through them one at a time. These subclasses are parsers, and I try to find them one by one that the parser parses some data correctly.

If I am not parsing, I call the function trynextto return the “next parser” to try. You can imagine that this operator switchcan get unyieldly if the constructors take arguments (all subclasses take the same arguments), and the more subclasses exist, etc.

- , - - ? , , [A, B, C], , , .

+1
1

(: "Parser" ), , , . : ();

(A, B, C...) .

Parsing ( , ), Parser.

forEach Parser.parse();... , , .

(A, B, C...) ( ). ParsingController ( ), , . , ( ).

UPDATE: , , .

UPDATE2: , , - / /.

import Swift

protocol Parser {
    func parse(code1: Int, code2: Int) -> Bool
}

extension Parser {
    var someCalculatedProperty: Int {
        return 12345
    }
    func someCommonMethod() {
        print("Some Common Method")
    }
}

class A : Parser {
    func parse(code1: Int, code2: Int) -> Bool { return false }
}
class B : Parser {
    func parse(code1: Int, code2: Int) -> Bool { return false }
}
class C : Parser {
    func parse(code1: Int, code2: Int) -> Bool { return true }
}

// Create 4 Parsers (two of the same type, just to demonstrate)
var parsers = [Parser](arrayLiteral: A(), A(), B(), C())

// Iterate the parsers until we get a success
for parser in parsers {
    if parser.parse(0, code2: 1) {
        print("Success")
        // Just for fun, call common parser methods.
        parser.someCommonMethod()
        print(parser.someCalculatedProperty)
        break
    } else {
        print("Fail")
    }
}

:

Fail
Fail
Fail
Success
Some Common Method
12345

3 ( A, A, B false) Success - C, true. .

+1

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


All Articles