Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix Any? cast to protocol always nil in ios 13 #2182

Merged
merged 2 commits into from
Dec 27, 2023
Merged

Conversation

wy-time
Copy link
Contributor

@wy-time wy-time commented Dec 19, 2023

It is a swift bug, In iOS 13 or earlier versions.
cast an Any? to protocol will always get nil
https://stackoverflow.com/questions/42033735/failing-cast-in-swift-from-any-to-protocol

In my case i use backgroundDecode option when download image, and if the image is a GIF the animate will lost, because the decode func not return itself

public func decoded(scale: CGFloat) -> KFCrossPlatformImage {
        // Prevent animated image (GIF) losing it's images
        #if os(iOS)
        if frameSource != nil { return base }
        #else
        if images != nil { return base }
        #endif
       ....... ........
    }

The frameSource always get nil, because the T in getAssociatedObject func is ImageFrameSource it is a protocol, so always return nil

func getAssociatedObject<T>(_ object: Any, _ key: UnsafeRawPointer) -> T? {
    return objc_getAssociatedObject(object, key) as? T // T is ImageFrameSource when get frameSource
}

The fix is first casting to AnyObject and then casting to the protocol
This swift bug was fixed in ios14 and macos 11 runtime

@onevcat
Copy link
Owner

onevcat commented Dec 25, 2023

@wy-time Thanks for reporting this. Umm, it is quite surprising.

I guess the similar issue might also happen on other platforms? Besides of only iOS and macOS, can you also try to add all of other supported platform versions to the check?

Maybe something like:

if #available(iOS 14.0, tvOS 14.0, macOS 11, watchOS 7.0, *) {
  //...

@wy-time
Copy link
Contributor Author

wy-time commented Dec 26, 2023

ok,swift 5.3 fixed this issue, so I add if #available(iOS 14, macOS 11, watchOS 7, tvOS 14, *) check

@onevcat onevcat merged commit ad51380 into onevcat:master Dec 27, 2023
4 checks passed
@onevcat
Copy link
Owner

onevcat commented Dec 27, 2023

Great! Thanks for it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants