Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static vs dynamic type

In Swift we can determine type of variable by type(of:) and Mirror(reflecting:).subjectType.

Documentation about Mirror.subjectType says:

The static type of the subject being reflected.

This type may differ from the subject’s dynamic type when self is the superclassMirror of another mirror.

I did not find docs for type(of:) but the proposal says that it's replacement for .dynamicType property.

So we have dynamic and static types. What the difference between them and in what circumstances does it show up?

P.S. I'm asking because I'm having strange issue. This code:

protocol A: class {
}

class B: A {
}

let b = B()

class C<T> {
    func test(value: T) {
        print("\(type(of: value))")
        print("\(Mirror(reflecting: value).subjectType)")
    }
}

func test(a: A) {
    print("\(type(of: a))")
    print("\(Mirror(reflecting: a).subjectType)")
}

C<A>().test(value: b)
test(a: b)

when running on iPhone from Xcode using Debug configuration gives output:

B
B
B
B

and running using Release configuration (switch to it under Product -> Scheme -> Edit -> Build Configuration -> Release) gives:

A
B
B
B

which seams to be a bug in Swift compiler.

UPDATE I opened JIRA ticket.

like image 871
mixel Avatar asked Apr 12 '26 19:04

mixel


1 Answers

The issue should be fixed in master now and in next (after 3.0.2) Swift version soon.

Thanks to Joe Groff.

like image 182
mixel Avatar answered Apr 17 '26 14:04

mixel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!