János János - 26 days ago 5x
Swift Question

Override method inline in Swift?

In JAVA I can create an object uses an interface, and override the method, do in the same spot. How is it possible in Swift?

JAVA Interface:

public interface ImageListener {
public void completed(Bitmap bitmap);

JAVA method call:

Utility.getImage(_id, "photo", new ImageListener() {
public void completed(Bitmap bitmap){

Swift protocol:

public protocol ImageListener {

func completed(image: UIImage?)

Swift method call? I tried something like this:

class MyImageListener : ImageListener {
func completed(image: UIImage?) {
imageView.image = image
Utility.getImage(item.id, attributeName: "image", completion: MyImageListener());

But get an irritating error:

enter image description here


You might use closures inline:

enum Utility {
    static func getImage(_ id: String, attributeName: String, completion: (_ image: UIImage) -> Void) {
        // get image here
        let image = UIImage()
        // pass image to handler

Utility.getImage("42", attributeName: "photo") { image in
    // your inline code with image processing