Skip to content

[SR-4450] "type(of:)" detects class type but returns false for "type(of:) is AnyClass" #47027

@regexident

Description

@regexident
Previous ID SR-4450
Radar rdar://problem/31372306
Original Reporter @regexident
Type Bug
Status Resolved
Resolution Done
Additional Detail from JIRA
Votes 0
Component/s Compiler
Labels Bug, Runtime
Assignee None
Priority Medium

md5: dc6ab6dfd3eb9653018884543bf399dc

Issue Description:

protocol Bar {}
class FooClass: Bar {}
struct FooStruct: Bar {}

func test1<T>(instance: T, `protocol`: T.Type) {
    let type = type(of: instance as Any)
    let typeIsClass = type is AnyClass
    print("\(type) is a class: \(typeIsClass)")
}

func test2<T>(instance: T) {
    let type = type(of: instance as Any)
    let typeIsClass = type is AnyClass
    print("\(type) is a class: \(typeIsClass)")
}

test1(instance: FooClass(), protocol: Bar.self)
test1(instance: FooStruct(), protocol: Bar.self)

test2(instance: FooClass())
test2(instance: FooStruct())

// test1:
// FooClass is a class: false
// FooStruct is a class: false

// test2:
// FooClass is a class: true
// FooStruct is a class: false

One would expect test1 to behave like test2.

type(of: instance as Any) was suggested by Joe Groff as a workaround for https://bugs.swift.org/browse/SR-4420, which revealed this bug.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugA deviation from expected or documented behavior. Also: expected but undesirable behavior.compilerThe Swift compiler itselfruntimeThe Swift Runtime

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions