iOS Development--swift & Classic Syntax (27) Swift and objective-c simple comparison

Source: Internet
Author: User

The comparison between Swift and Objective-c

Series (i)

WWDC 2014 on the Apple again a shocking launch of the new programming language Swift, this news before the slightest wind leaks. News release at that time, the venue exclaimed, I believe the world to watch live on the yards of farmers at that time also felt the head was knocked sap it. So stay up late to learn Swift Dafa, the more you see the more you want to shout "Swift Dafa good!" "

Programmers , the most attention is seeking truth from facts and objective, the following began to compare the two languages.

The first thing to emphasize is that Swift is definitely not an explanatory language, not a scripting language, and that, like Objective-c,c++, the compiler will eventually translate it into C language, In other words, the compiler eventually faces the C language code (this is true, no doubt!!!) So don't look at it long want scripting language, in fact it is more than Java, C # to be more efficient C language!!! , but Swift's strength is that it stands on the shoulders of all languages, absorbing the essence of all languages.

In this series, let's talk about some of the most basic grammatical changes:

    1. Swift finally gave up the objective-c moth-like [obj method:x1 with:x2] syntax, and finally followed the big stream, became the Obj.method () of the pleasing mode. Although for objective-c > programmer , these [] look really cool, you know how much of this < Span style= "color: #0000ff; font-size:18px; Width:auto; Height:auto; Float:none; " >c++ , java , C # Programmer? So this small change, can let is more approachable, and more friendly to people who have other language-based development.

But Apple is not so self-trivial, we know that the Objective-c method calls a grammar is not in other mainstream language, that is the label. When we use Java, C + +, C, C # and other languages, if using Rect.set (10, 20, 100, 500), although in the writing set method, the IDE has prompted the meaning of the four formal parameters, but after writing, this code in 10, 20, 100, 500 is the social meaning? So the readability of the code becomes very poor, and Objective-c solves the problem perfectly:

    1. [Rect setx:10 y:20 width:100 height:500]

Look! How great! Swift, of course, will not discard such a good tradition, as it is in Swift.

    1. Rect.set (Ten, y:20, width:100, height:500)

The following two points should be noted for the use of tags when calling methods:

1) Call of global function, no label can be used

    1. Fun (11, 22, 33)//correct
    2. Fun (N1:11, n2:22, n3:33)//Error

2) class function, the first parameter cannot be tagged

    1. Rect.set (y:100, width:300, height:200)//correct
    2. Rect.set (x:100, y:100, width:300, height:200)//Error

In fact, the definition of classes in Swift and Java, C # almost the same, no longer split files and. m files.

The definition syntax for a class is as follows:

    1. Class weapon
    2. {
    3. var name:nsstring
    4. var power:int
    5. Init (name:nsstring, Power:int)
    6. {
    7. Self.name = Name
    8. Self.power = Power
    9. }
    10. Func shoot ()
    11. }

Note : Statements in Swift do not require a semicolon to end.

Second, finally there are constructors and destructors!!! Objective-c, too? No NO NO!!!

There are no constructors in objective-c, and the real constructors are automatically called by the system, rather than forcing programmers to call them. Before forcing the programmer [[OBJ alloc] init], now finally finally the system automatically calls!

    1. Weapon weapon = Weapon (name: "Earth Cannon", power:100000000000)

I didn't write wrong, right! Now like Java, C #! Although weapon is a pointer, don't write that asterisk!! Because this star is scaring a lot of people! What Pointer?!! Ah ..... ”

C, C + + programmers Note that this weapon object is not allocated on the stack memory, is still alloc out, on the heap it.

    1. The most anticipated grammar has finally joined!

There's a problem with the override in Java,c++,objective-c, for a chestnut:

    1. @interface Weapon
    2. -(void) shoot;
    3. @end
    4. @interface Gun:weapon
    5. -(void) Shoot;
    6. @end

In large projects often encounter this problem, the programmer 's intention is to overwrite the shoot of the parent class, the result of hand tide .... Written in shoot, which has no grammatical errors, no logic errors, and results in

    1. weapon* currentweapon = [Gun new];

[Currentweapon shoot] is called the shoot method of the parent class (because the subclass is not overwritten at all, the subclass case is not carefully written wrong), this small error if it appears in the super-large project species is really difficult to find it!! Now, Swift finally solves this problem! When the subclass overrides the parent class method, be sure to write override before the method:

    1. Override Func shoot{
    2. }

In this way, the compiler look at the method before the override, it will be in the parent class to find out if there is a Shoot method, if you write wrong to the override Func Shoot, the compiler can immediately find the error!

Series (ii)

After the series was published, someone disagreed with my argument about #swift会取代objective-c#, and here I would like to highlight two points:

1) Swift is actually objective-c text variant, for this new language, < Span style= "color: #0000ff; font-size:18px; Width:auto; Height:auto; Float:none; " > > Apple's job is far less daunting than we thought. Llvm The compiler does the work by first putting Swift translate into Objctive-c code, and then translate the OBJECTIVE-C code into C code, and then translate the C code into a compilation, eventually translated into machine code. As for why compiler vendors are so wrapped around, not directly translating their own language into assembly and machine code, it is because the existing language compiler (OBJECTIVE-C, C) is already very mature, and the high-level language between the text conversion development costs and maintenance costs are extremely small. Why Swift translates into objective-c is due to the fact that Swift still needs objective-c ARC,GCD and other environments that are hard to build.

2) Since the SWIFT code will eventually be translated into objective-c by LLVM, what is the meaning of the swift language? Think of the arc just came out when everyone's reaction, many people and today's reaction, think I am a veteran objective-c, I know the way of memory management, constantly write [obj release], [obj autorelease] very cow, Only beginners can use the arc. The result is that in less than a year, arc ruled the entire horse industry, because we should be concerned about the business logic, and should not be distracted by the grammar and other low-level issues, the less time the grammar consumes us, the more successful the language.

Since Swift is actually objective-c, it is far more important to beginners than objective-c, and for senior developers it saves a lot of unnecessary, low-level repetitive mechanical code (which the compiler automatically helps you write when LLVM translates to objective-c). I can't think of any reason why Swift does not replace Objective-c.

Well, the argument is set aside, and we start from the beginning to see exactly how Swift has evolved.

1) The statement does not require a semicolon to end, and the variable does not require a type if it has initialization

    1. var n = 22

For the compiler, since you are initialized to 22, it certainly understands that n is int, you have hit enter, it certainly knows this is the end of the statement, so LLVM without pressure to translate it into

    1. int n = 22;

Of course, for multiple statements to put a line, the compiler will have no way, you still have to use a semicolon to end the statement. If there is no initialization, you can also manually specify the type of the variable

    1. var n = 22; var Hero:hero

So it looks like an untyped variable, essentially a strongly typed one (the compiler did it for you).

In the case of constants, let

    1. Let PI = 3.1415926

The pi here is constant, now think, the previous strong type of high-level language is stupid to no language ah, let pi = 3.1415926, pi is so obvious is a double, why also programmers to write double?!

2) Definition of function

    1. Func Test (P1:int, P2:int)
    2. {
    3. }

Call: Test (25, 100)//NOTE: Call to global function, parameter cannot be tagged

If there is a return value, the return type is denoted by the symbol "-"

    1. Func Add (P1:int, P2:int)->int
    2. {
    3. Return P1+P2
    4. }

3) Definition of class

No more split files and M files! This is identical to Java, C #

    1. Class Person
    2. {
    3. var name:string
    4. var age = 0
    5. Init (name:string, Age:int)
    6. {
    7. Self.name = name;
    8. Self.age = age;
    9. }
    10. Func description ()->string
    11. {
    12. Return "name:\ (Self.name); Age: ' (age) ";
    13. }
    14. }

Notice finally there is a constructor!! Init is automatically called by the system and does not need to be called manually by the programmer . So it can be written as well as ordinary functions, which cannot be added in front of Func. Why does the compiler want to do this? Because if Init is allowed to precede with func, in case the programmer accidentally writes the INIT function name incorrectly, as Func inot (), the compiler is completely unaware that it is the constructor that the programmer wants to write. Now the constructor does not add func if you write Inot (). Compiler a look at the front without func know you want to write the structure, the function name is not init, the compiler will know you accidentally write wrong can immediately error!!

4)# optional variable # --all high-level languages begin with a puzzle

For example, customers need to provide a final API, the customer gives you a data source, need to find in the data source name is "JACK.XU" student scores. The design of this API should look like this:

    1. int Findscorebyname (datasource* source, string* name);

The question comes, if the "Jack.xu" student does not exist at all, should return what? return 0? That must be wrong, because 0 may also be the result of the student. Of course, if the object returned is a class, return null directly, the caller knows not found, is now the basic data type, return null is actually 0, how to do? (The canonical practice in c,c++ is to return a bool to indicate whether it is found, and the result is passed by formal parameters, and other high-level languages can encapsulate a small class/package Class)

In response to this problem, Swift has specifically designed a variable called "optional value (optional variable)" to solve this problem.

Grammar:

    1. var n:uint? = 5 or var n? = 5

In here? Indicates that n is an optional variable, which means that n may not exist, and under what circumstances does n not exist?

If you write like this:

    1. var n:uint?

In addition, it is important to note that in swift syntax, nil is not 0, but a variable of type Niltype

So the problem mentioned above can be easily solved.

    1. Func findscorebyname (Source:datasource, name:string)->uint? An optional variable is returned
    2. {
    3. var score:uint?; The score variable does not allocate memory at this time, which means that score is nil
    4. if (source. Hasstudent (Name:name))
    5. Score = source[Name].  Score; Here score only allocates memory;
    6. return score; If no student information is found, score's memory has not been assigned
    7. }

iOS Development--swift & Classic Syntax (27) Swift and objective-c simple comparison

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.