Swift and Objective-C: New Understanding of Apple's programming language (1)

Source: Internet
Author: User

BKJIA Translation: no matter whether the result is good or bad, the brand-new language developed by Apple will allow us to handle development work in our own way.

For anyone other than apple, it is hard to assert the follow-up effects of the sudden release of the Swift language. InThis WWDC ConferenceIn the keynote speech, Apple kept releasing the news we expected, although some of the details were indeed surprising, released its modern Objective-C alternative-Swift. In fact,Swift Programming LanguageIt was used for project development for a short time after Steve Jobs founded NeXT.

Swift is by no means the type of announcements that will be officially launched by the end of this year. On the same day, the iBooks store published a 550-page Swift Language Development Guide.The official Swift tutorial of apple is completed in Chinese within 9 days and can be read online.). Developers can also experience the Xcode 6 beta version, which allows us to use this new language for application development. All in all, all the elements and changes necessary for Swift to smoothly collaborate with the Cocoa toolkit are ready, and only the developers are here to learn.

Although Swift has not been officially used for code development, we have read through the entire language user guide and read the sample code provided by Apple. What we need to do next is to use this language and understand what Apple wants to achieve with it.

Why should we use Objective-C?

At the beginning of NeXT's establishment, object-oriented programming mechanisms were not widely used, and even few languages were able to truly implement this idea. At that time, Objective-C may be the most ideal solution we can choose-it can maintain the availability of the original C code and the traditional usage habits of developers, on the other hand, an object-oriented layer is added.

However, it turns out that NeXT is the only mainstream vendor that uses the language. From a certain point of view, this also brings about some positive factors. After all, the company can focus on creating its own entire Objective-C development environment from scratch without any worries. Naturally, any user who intends to use the language for software development will inevitably use the NeXT solution. For example, many "language features" in Objective-C do not actually belong to true language features. They actually come from the basic classes created by NeXT, that is, NSObject. In addition, some design patterns in Coca, such as the existence of delegates, you also need to use the introspection function in Objective-C-it is used to safely detect whether an object will respond to a specific message.

Objective-C's extremely limited use area also has a negative impact, that is, forcing the language to face the niche market. When Apple inherited Objective-C, the technicians immediately started to provide a backup solution for developers, that is, the Carbon library, this is done to ensure that the development method is closer to the traditional Mac software development process.

The rapid popularity of the iPhone SDK has turned things around. Since it only allows developers to choose Objective-C, this object-oriented language has begun to spread across the world. It seems that overnight, developers began to use Objective-C, many of which even left aside their years of experience using other programming languages. This is undoubtedly great news for Apple, but it also brings about some problems. Not every developer is willing to use Objective-C, apple subsequently adopted a method we all know to solve this problem-announcing that the future of Mac development will be undertaken by the Cocoa Objective-C framework.

What's the problem with Objective-C?

Objective-C has always had incredible tacit understanding and unexpected harmony with Apple. By strictly controlling runtime and compiling its own compiler, the technology giant has the ability to add a series of new features to it while avoiding language limitations that come from the NeXT age, for example, the property, the garbage collection mechanism, and the alternative product of the garbage collection mechanism-automatic reference counting.

However, some situations cannot be changed. Since it is still a derivative product of C language that has been extended to a certain extent, Objective-C can only use the C method to track complex objects, that is, pointer-pointer is basically the first byte of the memory address occupied by the object. Everything, from NSString to the most complex table view, needs to use its pointer for transmission and communication.

In most cases, this mechanism does not produce problems. When writing complex applications, we basically don't realize that we have used pointers that are unknown and uncommon. But in some rare cases, this mechanism will also mess up everything and try to access the wrong memory address, resulting in program crash or bring unexpected security vulnerabilities. In fact, some other features of the C language can cause similar drawbacks. Developers must carefully check the length of their code and endure the restrictions, otherwise, the Code may wander to other random locations in the memory.

In addition to this kind of inherent deficiency, Objective-C gradually becomes old over time. With the continuous development of technology, other programming languages have some outstanding features that are difficult to be transplanted to antique development solutions such as C language. The most typical example is "generic ". In C, if we want to perform the same mathematical procedures for integers and floating point values, you must write an independent function for each of them-plus additional functions specifically used for other unsigned long integers and double-precision floating point values. With the help of generic, You can compile a function separately to easily ensure that all values are correctly recognized as numbers by the compiler.

Apple apparently can add some important features in the Objective-C syntax-closure is a good example-but we do not know whether they can add such features as they wish. Moreover, the natural properties of C language mean that it always has security risks. After all, all stability and security tasks are undertaken by a single set of encoder without careful consideration. It can be said that it is time to change everything.

But why not simply choose another existing language? This is because Objective-C is closely related to the Cocoa framework, and a series of design patterns used by Objective-C can significantly improve the execution efficiency of the framework. Most of the existing mainstream alternatives cannot smoothly collaborate with the existing Cocoa framework in such a concise manner. In view of this, Swift came into being.

Shot at 2014WWDC

Okay, but why?

There are several reasons. With the migration of the development system to LLVM, Apple has firmly controlled its runtime and tool chain. This makes solution changes easier to implement and fully understand the consequences. At the same time, Apple has accumulated rich experience in language development and successfully brought new features such as attributes, automatic reference counting, and closure to Objective-C.

These changes have also made Apple initially feel how developers may respond to the changes in the future. When Apple introduced the garbage collection mechanism and declared to developers that "this is an outstanding solution", the feedback can be said to be good or bad. Later, when Apple introduced automatic reference computing and said "This represents the future", developers began to adapt to this new situation at a faster speed. Apple's decision to cut 64-bit Carbon will undoubtedly help developers predict the date of release of the new language .)

All these early changes have helped the launch of some of Swift's new features clear the way. We may recall that closure and auto-reference counting have not been available for a long time. The variable processing method is quite similar to the Objective-C attribute. Moreover, because Apple strictly controls everything, the same runtime can support Swift and Objective-C in parallel, that is, the smooth connection between the legacy code running and the new language. All in all, the announcement of such a decision may have devastating consequences five years ago, but now Swift has a mass base for smooth succession.

We may never know how long before Apple began planning the launch of the Swift programming language, but considering Apple's practical experience in the past five years, you will find that they have been accumulating experience, making tentative actions, and observing the tolerance of the developer community for such changes.

Do you understand what I mean?

If you plan to write a new programming language, the primary challenge is to make a trade-off between ease of use and readability. As the most simple demo, we have selected the original example in the Swift developer instruction document. If we write the following code, even readers who are not familiar with programming can see some clues.

 
 
  1. if thisIsTrue { 
  2.  
  3.     that = that + 50 
  4.  
  5. } else { 
  6.  
  7.     that = that + 20 
  8.  

However, if you directly use the following code expression, most people may feel confused:

 
 
  1. that = that + (thisIsTrue ? 50 : 20) 

The above two sections of Code actually express the same meaning. The second type is more concise and can greatly reduce the input burden, while the first type is more simple and easy to understand. Programming Language designers must make a series of decisions to balance the two. These decisions may ultimately have a profound impact on the fate of the programming language. After all, readability affects the beginner's ability to get started quickly and understand the meaning of the code sample, or allow developers to take over the project quickly in case of comments and poor comments.

Unless you have a way to understand the meaning of these parentheses, Objective-C performs poorly in terms of readability. If you write a function to extract the text between two strings, the entire implementation process in most programming languages is usually as follows:

 
 
  1. myString.getTextBetweenBrackets( leftBracket, rightBracket); 

However, in actual use, these variables are often unable to use such random naming methods. Unless you can keep this function in your mind, you must remind yourself of the order of adding the two parentheses. Objective-C chooses to add a part of the input cost to avoid the risk of ambiguity. The code for the same meaning is as follows:

 
 
  1. [myString getTextBetweenLeftBracket: leftBracket andRightBracket: rightBracket]; 

It is very useful to specify the actual function of each parameter, which means that we can increase the number of parameters, but it also reduces the self-interpretation ability of variable names. Swift is quite a mix of the two, but it also exactly retains the following expression:

 
 
  1. myString.getBracketedText ( LeftBracket: leftBracket, rightBracket: rightBracket ); 

This is a very important way of processing, and the readability is guaranteed here. However, every developer who is dissatisfied with the features mentioned in Objective-C will also feel resentful about Swift. Perhaps we should say that readability can be ensured. After all, Swift also allows you to skip the process of adding the method symbol to the brackets. Apple recommends that you write these additional texts correctly, but I guess many of them will not have their own set .)

In many other aspects, the readability of Swift is indeed worrying. The most important thing is that the existence of a single character, such as an exclamation point or question mark, may have a huge impact on the entire function call chain, or even completely change the execution efficiency of the entire line of code. You can use the function definition method to deal with such problems, such as setting the default value and setting the internal and external names for the parameters, however, this means that we must carefully read the content of the function to ensure that we understand its actual function.

Next let's take a look at another example from the Swift Programming Language Development Guide. Let's take a look at how to define a set of planetary enumeration:

 
 
  1. case Mercury = 1, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune 

We only need to add a set of indexes for the first entry. If there are no other operations, the compilation assumes that we want to start from 1 and perform auto-incrementing accordingly. This works well and can help programmers save a lot of time. However, if you happen to forget that Saturn is the sixth planet in the solar system-or you happen to be dealing with a list of relatively hard-to-remember content-you may find that you need to waste a lot of time deciding which number which entries correspond.

What is the impact of this feature on our personal orientation in terms of readability and writability? The answer remains uncertain until we thoroughly use this language and read more sample code. As far as the current situation is concerned, it is difficult for a large number of Swift code to understand its meaning through direct reading. However, we feel that this is not the primary focus in actual use. Most programmers may prefer Swift's relatively compressed syntax, however, the flexibility of this language may mean that people intentionally or unintentionally write code content that is no problem in actual operation but hard to understand by other users.


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.