3

I'm coming from Java and now I would like to make abstract class in Swift.

I have this class in Java , and I want to make the same in Swift if possible

abstract class Fetcher
{
    private Item[] items;
    public void fetch()
    {
        //SOME CODE
        parse();
        //SOME CODE
    }

    public abstract void parse();
}

So , is there a way to achieve the same in Swift I wont mind using any hacks is it was the last hope

Ali Faris
  • 17,754
  • 10
  • 45
  • 70

1 Answers1

9

Swift unfortunately doesn't support abstract classes and methods.

To achieve a similar effect, in Swift we use protocols (Interfaces in Java).

So an example of your class would be:

protocol Fetcher {
    var items: [Item] { get set }
    func fetch()
    func parse()
}

The one thing you can do, is mark members of a class final to prevent them from being overridden in their subclass.

If you want a default implementation of one of your functions, you extend your protocol:

extension Fetcher {
    func fetch() {
        //SOME CODE
        parse()
        //SOME CODE
    }
}

In which you won't need to implement this in your target class.

So for example, using the above protocol:

class Foo: Fetcher {
    var items = [Item]()

    // No need for fetch method, since it's already implemented

    func parse() {
       // Do something
    }
}

Note, that the above implementation doesn't contain the method fetch since it's already implemented in the protocol extension.

vikingosegundo
  • 52,040
  • 14
  • 137
  • 178
Dejan Skledar
  • 11,280
  • 7
  • 44
  • 70