Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to understand the reference type or "Pointer" in Swift?

Tags:

swift

Pointers

If you have experience with C, C++, or Objective-C, you may know that these languages use pointers to refer to addresses in memory. A Swift constant or variable that refers to an instance of some reference type is similar to a pointer in C, but is not a direct pointer to an address in memory, and does not require you to write an asterisk (*) to indicate that you are creating a reference. Instead, these references are defined like any other constant or variable in Swift.

Here is the interpretation of "Pointers" from Apple doc. We all know that in C++ or Objective-c, the pointer point directly to the address in memory. But in Swift, Apple says A Swift constant or variable that refers to an instance of some reference type is similar to a pointer in C, but is not a direct pointer to an address in memory, it confuses me a lot. My question is what is the scene behind reference type, if it is not a direct pointer to an address in memory, where is it point to?

Any hint or clue will be greatly appreciated.

like image 951
Burrows Wang Avatar asked Nov 17 '15 05:11

Burrows Wang


People also ask

What is reference type in Swift?

Types in Swift fall into one of two categories: first, “value types”, where each instance keeps a unique copy of its data, usually defined as a struct, enum, or tuple. The second, “reference types”, where instances share a single copy of the data, and the type is usually defined as a class.

What is the difference between reference type and pointer type?

References are used to refer an existing variable in another name whereas pointers are used to store address of variable. References cannot have a null value assigned but pointer can. A reference variable can be referenced by pass by value whereas a pointer can be referenced by pass by reference.

Which is better pointer or reference?

References are usually preferred over pointers whenever you don't need "reseating". This usually means that references are most useful in a class's public interface. References typically appear on the skin of an object, and pointers on the inside.

What is difference between reference and pointer with example?

Pointers: A pointer is a variable that holds the memory address of another variable. A pointer needs to be dereferenced with the * operator to access the memory location it points to. References: A reference variable is an alias, that is, another name for an already existing variable.


1 Answers

Classes are references types, so variables (var) and constants (let) that reference them are effectively pointers "behind the scenes". What the documentation is trying to get at is that this is hidden from the programmer. There are no pointer operators in Swift.

like image 119
Charles A. Avatar answered Oct 20 '22 01:10

Charles A.