简体   繁体   中英

Assign value to variable from closure - iOS Swift

Im trying to assign Image (which downloads from API) from closure to a variable. Closure which implements execution is an escaping closure.

Since thats escaping closure, I receive "Missing return in a function expected to return 'UIImage?'"

Kindly advice how to fix this

 var posterPath: UIImage? {
    get {
        let url = posterData.medium[0].url
        self.imageFor(for: url) { (image) in
            return image
        }
    }
  //returns error here as there is no return statement
}

I think you can achieve this by having an escaping param in your function, something like this:

func getTheImageFromApi(success: @escaping (_ image: UIImage) -> ()){

    let url = posterData.medium[0].url
        self.imageFor(for: url) { (image) in
            success(image)
     }

}

Then using this function in your view controller:

var posterPath: UIImage?

override func viewDidLoad() {
    super.viewDidLoad()

    getTheImageFromApi(success: { image in
        self.posterPath = image
    })
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM