在Swift中内联覆盖方法?

时间:2016-09-29 09:59:49

标签: java swift interface

在JAVA中我可以创建一个使用接口的对象,并覆盖该方法,在同一个地方做。 Swift怎么可能?

JAVA界面:

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

JAVA方法调用:

Utility.getImage(_id, "photo", new ImageListener() {
          public void completed(Bitmap bitmap){
         userSettingHolder.icon.setImageBitmap(bitmap);
   }
});

Swift协议:

public protocol ImageListener {

    func completed(image: UIImage?)
}

Swift方法调用?我试过这样的事情:

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

但是得到一个恼人的错误:

enter image description here

1 个答案:

答案 0 :(得分:1)

您可以使用内联闭包:

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

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