Skip to content

[SR-8787] type(of:) not returning dynamically-created subclasses #51295

@swift-ci

Description

@swift-ci
Previous ID SR-8787
Radar None
Original Reporter johnestropia (JIRA User)
Type Bug
Status Resolved
Resolution Won't Do
Additional Detail from JIRA
Votes 0
Component/s Standard Library
Labels Bug
Assignee None
Priority Medium

md5: c0e5a08424340faee038a65df080116f

Issue Description:

I have a Swift class "CoreStoreManagedObject" which subclasses NSManagedObject. More subclasses of this type are created with "objc_allocateClassPair()", and then some NSObject methods are overrided dynamically using "class_addMethod()", in my particular case, "keyPathsForValuesAffectingValueForKey:".

Until Swift 4.1,

type(of: object).keyPathsForValuesAffectingValueForKey("someKeyPath")

always worked as expected, returning values funneled through the created subclasses. In Swift 4.2, "type(of🙂" seems to return the compile-time class (which returns nothing). I am not sure if this is by design or if I hit a rare edge case.

For now I work around this by writing

func cs_dynamicType<T: AnyObject>(of instance: T) -> T.Type {
    
    return object_getClass(instance) as! T.Type
}

and using it in place of "type(of🙂"

I reproduced this with the Unit tests in the library https://github.com/JohnEstropia/CoreStore

Commit: 40f458a09c0177d15ceab1561acaede2799c4f2d (post-fix)

Replace "cs_dynamicType(of🙂" usage in "DynamicModelTests.swift" back to "type(of🙂" to reproduce Unit Test failure.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugA deviation from expected or documented behavior. Also: expected but undesirable behavior.standard libraryArea: Standard library umbrella

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions