This article introduces the Swift Runtime mechanism. I’m sure you all know a little bit about classes in Objective-C. Even if you haven’t studied it, you’ve probably heard that a Class is actually a structure, and a structure contains such terms as ISA and superClass. So this paper is to study the nature of Swift class and its runtime principle.

Start with a new Xcode project and select the Command Line Tool to keep other factors from interfering

The directory structure for generating projects is very simple

Swift // Runtime // // Created by XXX on 2020/4/19. // Copyright © 2020 Runtime. All rights reserved. // import Foundation print("Hello, World!" )Copy the code

Next delete all code including comments except print(“Hello,World”) and add a breakpoint at print(“Hello,World”)

Next we define a Person class and add the following code to the top of print(“Hello,World”) :

class Person {
    
}
var a = Person()
var b = Person()
var c = Person()

print("Hello, World!")
Copy the code

And then let’s run it, because of the breakpoint, it will stop at print(“Hello,World”). You can see that the variables A, B, and C were successfully assigned.

X /2gx

0x0000000100002108

class Person {
    
}
class animal {
    
}
var a = Person()
var b = Person()
var c = Person()

var d = animal()
var e = animal()
var f = animal()

print("Hello, World!")
Copy the code

0x0000000100002198
0x0000000100002228
0x0000000400000002
0x0000000200000002

class Person {
    
}

var a = Person()

print("Hello, World!")
Copy the code

var b = a

class Person {
    
}

var a = Person()
var b = a
print("Hello, World!")
Copy the code

var c = a

class Person {
    
}

var a = Person()
var b = a
var c = a
print("Hello, World!")
Copy the code

0x0000000200000002
0x0000000400000002
0x0000000600000002
var b = a
var c = a
Swift, the source of
The document

struct HeapObject {
  /// This is always a valid pointer to a metadata object.
  HeapMetadata const *metadata;
  InlineRefCounts refCounts
}
Copy the code

Where metadata is a pointer to adata structure that describes type information, and refCounts, as the name suggests, is adata structure that counts references. Therefore, the corresponding results can be obtained in our preliminary study. The instance variable is the HeapObject structure, and the class information and its own reference count are saved. Next we’ll take a closer look at the metadata and refCounts.

Swift Runtime(2)- Reference count