0

Please, help me to make interface in Swift to use it for callbacks purposes.

Example in Java:

public interface ErrorListener {
    void onError(String errorMsg);
}

class SomeUiClass implements ErrorListener {

    public SomeUiClass () {
        SomeWorkingClass s = new SomeWorkingClass();
        s.setErrorListener(this);
        s.doSomething(true);
    }

    @Override
    void onError(String errorMsg) {
        System.out.println("Error msg: " + errorMsg);
    }
}

class SomeWorkingClass {

    ErrorListener listener;

    void setErrorListener (ErrorListener listener) {
        this.listener = listener;
    }

    void doSomething (boolean withError) {
        if (withError) listener.onError("Test error");
    }

}


//....
SomeUiClass ui = new SomeUiClass(); // prints: Error msg: Test error 

So, I tried to use protocol in Swift for this purpose, but I didn't understand, how to use it properly.

1 Answer 1

1

It would look like this in swift

protocol ErrorListener {
    func onError(errorMsg:String)
} 
class SomeUiClass : UIViewController ,  ErrorListener { 

    func onError(errorMsg:String)
        print("Error msg: ", errorMsg)
    }
}

class SomeWorkingClass : UIViewController{

    weak var listener:ErrorListener?

    func setErrorListener (listener:ErrorListener) {
        self.listener = listener
    } 
} 

let ui = SomeUiClass() // prints: Error msg: Test error 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.