Search code examples
iosswiftcgcolorlottie

How do I return an Unmanaged<CGColor>! in Swift


I'm using Lottie (animation framework) and one of the delegates I'm trying to use is expecting me to return an Unmanaged<CGColor>!

This is the definition:

color(forFrame currentFrame: CGFloat, startKeyframe: CGFloat, endKeyframe: CGFloat, interpolatedProgress: CGFloat, start startColor: CGColor!, end endColor: CGColor!, currentColor interpolatedColor: CGColor!) -> Unmanaged<CGColor>!

If I just try to return UIColor.white.cgColor I get an error that says

Cannot convert return expression of type 'CGColor' to return type 'Unmanaged<CGColor>!'

I already tried going through their documentation but their example only shows to use it like this:

let colorBlock = LOTColorBlockCallback { (currentFrame, startKeyFrame, endKeyFrame, interpolatedProgress, startColor, endColor, interpolatedColor) -> Unmanaged<CGColor> in
    return aColor
}

So how can I return the proper type?

Thanks


Solution

  • You can create Unmanaged instance by calling passRetained or passUnretained static function like this:

    Unmanaged.passRetained(UIColor.white.cgColor)

    But keep in mind, that for future usage of this variable should be handled with takeRetainedValue if you decided to use passRetained() or with takeUnretainedValue() function if you will use passUnretained. If that would not be done - you would have memory leak or possible crash.