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:
- 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:
- [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.
- 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
- Fun (11, 22, 33)//correct
- Fun (N1:11, n2:22, n3:33)//Error
2) class function, the first parameter cannot be tagged
- Rect.set (y:100, width:300, height:200)//correct
- 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:
- Class weapon
- {
- var name:nsstring
- var power:int
- Init (name:nsstring, Power:int)
- {
- Self.name = Name
- Self.power = Power
- }
- Func shoot ()
- }
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!
- 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.
- The most anticipated grammar has finally joined!
There's a problem with the override in Java,c++,objective-c, for a chestnut:
- @interface Weapon
- -(void) shoot;
- @end
- @interface Gun:weapon
- -(void) Shoot;
- @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
- 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:
- Override Func shoot{
- }
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
- 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
- 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
- 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
- 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
- Func Test (P1:int, P2:int)
- {
- }
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 "-"
- Func Add (P1:int, P2:int)->int
- {
- Return P1+P2
- }
3) Definition of class
No more split files and M files! This is identical to Java, C #
- Class Person
- {
- var name:string
- var age = 0
- Init (name:string, Age:int)
- {
- Self.name = name;
- Self.age = age;
- }
- Func description ()->string
- {
- Return "name:\ (Self.name); Age: ' (age) ";
- }
- }
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:
- 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:
- 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:
- 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.
- Func findscorebyname (Source:datasource, name:string)->uint? An optional variable is returned
- {
- var score:uint?; The score variable does not allocate memory at this time, which means that score is nil
- if (source. Hasstudent (Name:name))
- Score = source[Name]. Score; Here score only allocates memory;
- return score; If no student information is found, score's memory has not been assigned
- }
iOS Development--swift & Classic Syntax (27) Swift and objective-c simple comparison