Swift Learning notes-----pointers in Swift

Source: Internet
Author: User

In order to simplify the swift language, the pointer is cloaked. There is no "*" like that in OC. Give the underlying question to the C language, and we can call the C language in Swift to solve it. Of course, OC can also be called.

However, in some scenarios, this invocation may not be very convenient. For example, based on the parsing of the byte stream, the data we receive is parsed, and pointers may be used. If you call it in C, you can, of course. But if you want to write a little more concise, it is possible to use Swift to deal with these directly. It's important to see if it's good to use pointers in Swift.

In fact, Swift is a support for using pointers. Apple has already disclosed Swift's source code, which everyone can go to see. The source code is written in C + +. But since it is a new language, but also to avoid the old way OC walked. So you can't just use pointers directly as you would in OC. In swift, pointers are mapped for a generic type and are also more abstract. This has, to some extent, caused the difficulty of using pointers in Swift. Even so, it can be used, so this is what makes the byte stream parsing possible in Swift.

First, the definition of the pointer

In Swift, how do we define pointers? Like what:

   let  tmpint   =  20 ;    let  ptr      =  &tmpint; 
    so the compilation does not pass. So you can't use it that way.        For example, in C, allocate memory space, and then assign values, which can be written like this.        first request memory Space    int * ptr =  (int*) malloc ( sizeof (int) *);       writes data to the requested memory space according to the address    *ptr = 10;        This we use Swift to write, written in the form below.    var intptr = unsafemutablepointer<int>.alloc (1);    print ("Intptr = \ (INTPTR)");       printing can be assigned to the space of the address, generally speaking is the first address of 4 bytes.     Thus, we can see that in swift, we mainly use several forms of unsafemutablepointer to     do pointers operations         How do you do it in swift by assigning values to the corresponding memory space through pointers?        like C, direct access to memory space    intPtr.memory = 20;    print ("The value after assignment in C is  \ (intptr.memory)");       by printing, you can see that the value of the memory space has indeed been changed.        except in this way,You can also use another way to allocate space before initializing       var intptr = unsafemutablepointer <int>.alloc (1);    intptr.initialize,    print ("IntPtr = \ ( INTPTR)    print ("Intptr value =\ (intptr.memory)");        with the code above, you can see the same as C.     second, the release of memory     in C and C + +, we apply the principle of heap space is "who applies, who releases". In OC, the mechanism of the MRC was used in the early stages, and the arc mechanism was later applied. So in swift, do we need to release the memory space we're applying for? The answer is clearly that it needs to be released. As in C, let's take a look at the complete wording of the C language.       //Request memory space, 4 bytes    int * ptr =  (int*) malloc (sizeof (int.));    //by pointers, assigning values    *ptr = 30;
Use done to free up space
Releases the memory space that PTR points to free (PTR);        Set the value of the pointer variable to null PTR = null; So how do you free up memory in Swift?        Let's look at the complete process.    1. Apply 4 bytes of memory space var intPtr = Unsafemutablepointer<int>.alloc (1);        2. Initialize the value of the memory space, or assign a value directly to the memory space Intptr.initialize (10);  After the use is complete, free the memory Space Intptr.destroy (); 1. Used to destroy Objects Intptr.dealloc (1);     2. Release the memory space pointed to by the pointer intPtr = nil; 3. The pointer is set to a null pointer

As you can see, Swift's memory release process is more complex than the C language.


Third, in the function of the use of the parameter

The 1.C language uses pointers in function-pass arguments. This is a small example of the C language we are looking at first. Such as:

    //defines a variable a of type int and assigns a value to a     int a = 10;     //defines a function that modifies the value of variable a by using the function.     void changedata (Int * tmpa,int value)     {         *tmpA = value;    }         //we call this function to modify the value of variable a     changedata (&a,100);     //prints the value of a     printf ("a = %d\n", a);      Use         var tmp = 20;  in    2.swift    //defines the function in Swfit     func incrementor (ptr:unsafemutablepointer<int >)     {       ptr.memory += 10;     }    //Call the function     incrementor (&tmp); &nbsp,    print ("Tmp = \ (TMP)");     in Swift, can also be used in functions by inout this keyword      //defines the function, using the keyword inout    func testpointuse (inout num:int) {        num += 1    }    //Call this function , note that the parameter of this place is to be added with the address symbol.     testpointuse (&tmp);     print ("Tmp = \ (TMP)");        pointers to arrays      in swift, how do you point to an array with pointers?     //defines an array of Swift     var array = [1,2,3,4,5];     //defines a pointer to the array, whose arguments are the address and array of the count    var arrayptr =  Unsafemutablebufferpointer<int> (Start: &array, count: array.count)      var basePtr = arrayPtr.baseAddress as UnsafeMutablePointer<Int>;     print ("Baseptr. memory = \ (Baseptr.memory) ");     print (" Baseptr = \ (BASEPTR) ");     baseptr.memory = 10;    print ("BasePtr.memory = \ ( baseptr.memory)     print ("Baseptr = \ (baseptr)");     var  nextptr = baseptr.successor ();     print ("Nextptr.memory = \ ( Nextptr.memory) ");

Swift has fewer pointers, but in the current development of smart home appliances, if you use Swift instead of OC, or if your code is migrating from OC to Swift, then this pointer method has a number of functions. Of course, in OC, you can use C directly. This is no problem. But when your project moves to Swift, these functions will be implemented in C and then invoked with Swift, which is certainly not wrong. Sometimes the call feels uncomfortable, so you can use Swift to try it out. See if we can rewrite the functions written in C with Swift. In this way, our project, for new people, especially those who have a weak C language skills, do not have to look at the C function every time. The modifications have also become straightforward.

Of course, this is only my opinion, we have the wrong place in the text, if there is time, can communicate more.


This article is from the "Liu Yufeng" blog, make sure to keep this source http://liuyufeng.blog.51cto.com/4428859/1747464

Swift Learning notes-----pointers in Swift

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.