p-x9 / AssociatedObject

🔗 Swift Macro for allowing variable declarations even in class extensions
MIT License
126 stars 3 forks source link

Force unwrapping will crash. #36

Closed mlch911 closed 5 months ago

mlch911 commented 5 months ago

Maybe we should treat force unwrpping as same as optional ?

Code:

@available(iOS 16.0, *)
@AssociatedObject(.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
private var interaction: ImageAnalysisInteraction! = .init()

Expanded:

{
    get {
        if !self.__associated_interactionIsSet {
            let value: ImageAnalysisInteraction! = .init()
            objc_setAssociatedObject(
                self,
                Self.__associated_interactionKey,
                value,
                .OBJC_ASSOCIATION_RETAIN_NONATOMIC
            )
            self.__associated_interactionIsSet = true
            return value
        } else {
            return objc_getAssociatedObject(
                self,
                Self.__associated_interactionKey
            ) as! ImageAnalysisInteraction  // <-- This force unwrapping will crash if value is nil.
        }
    }
    set {
        objc_setAssociatedObject(
            self,
            Self.__associated_interactionKey,
            newValue,
            .OBJC_ASSOCIATION_RETAIN_NONATOMIC
        )
    }
}
p-x9 commented 5 months ago

This is a problem because it is certainly possible to assign nil. I think the following part is the cause.

https://github.com/p-x9/AssociatedObject/blob/a82277a628bf40251c4459794ed1503b7ace06c1/Sources/AssociatedObjectPlugin/AssociatedObjectMacro.swift#L256

I will fix it later. Thanks.