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, more than a scripting language, it is the same as objective-c,c++, the compiler will eventually translate it into C language, that is, the compiler finally face is actually 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, into the Obj.method () of the pleasing mode. Although for OBJECTIVE-C programmers, these [] look really cool, you know how many C + +, Java, C # programmers scare the brackets away? So this small change can make Apple's development more approachable and friendlier to people who have other languages to develop.
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:
C code
- [Rect setx:10 y:20 width:100 height:500]
[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.
C code
- Rect.set (Ten, y:20, width:100, height:500)
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:
C code
- class weapon
- {
- var name:nsstring
- var power:INT  
- init ( name:nsstring, power:int )
- {
- self.name = name
- self.power = power
- }
- func shoot ( )
- }
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!
C code
- Weapon weapon = Weapon (name: "Earth Cannon", power:100000000000)
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:
C code
- @interface Weapon
- -(void) shoot;
- @end
- @interface Gun:weapon
- -(void) Shoot;
- @end
@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
C code
- weapon* currentweapon = [Gun new];
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:
C code
- Override Func shoot{
- }
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 a objective-c text variant, and for this brand-new language, Apple's work is far from as daunting as we imagined. LLVM compiler to do the work just first translated Swift into Objctive-c code, and then the OBJECTIVE-C code translated into C code, and then the C language code translated into a compilation, and 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
C code
- var n = 22
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
C code
- int n = 22;
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
C code
- var n = 22; var Hero:hero
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
C code
- Let PI = 3.1415926
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
C code
- Func Test (p1: int, p2: int)
- {
- }
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 "-"
C code
- Func Add (p1: int, p2: int),int
- {
- return P1+P2
- }
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 #
C code
-
- 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) ";
-
- }
-
- }
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:
C code
- int Findscorebyname (datasource* source, string* name);
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:
C code
- var n:uint? = 5 or var n? = 5
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:
C code
- var n:uint?
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.
C code
- func findscorebyname ( source:DataSource, name:String )->uint? //returns an optional variable
- {
- var score : UInt ?; //at this time the variable of score is not allocated memory, that is score nil
- if ( source. Hasstudent ( name: name ) )
- score = source[ name ]. score; // This score only allocates memory;
- return score; //if no student information is found, score memory has not been assigned
- }
Func FindScoreByName( source:DataSource, name:String )->UInt? //Returns an optional variable
{
Var score : UInt ?; //The variable of score is not allocated memory at this time, that is, the score is nil
If( source.HasStudent( name: name ) )
Score = source[ name ]. score; //The score is allocated memory here;
Return score; / / If the student information is not found, the score memory has not been assigned
}
The comparison between Swift and Objective-c