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

1.4k Views Asked by At

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

2

There are 2 best solutions below

1
Taras Chernyshenko On BEST ANSWER

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.

1
Ahmad F On

You could get it by using takeRetainedValue() method in Unmanaged structure:

Gets the value of this unmanaged reference as a managed reference and consumes an unbalanced retain of it.

In your case, the instance type should be CGColor, therefore:

let cgColor = unmanagedColor.takeRetainedValue()

should solves it. Note that unmanagedColor is the output of calling the definition you mentioned:

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


Furthermore, you might want to check:

When to use takeUnretainedValue() or takeRetainedValue() to retrieve Unmanaged Objects in Swift?