Comparison between Swift and Objective-C, SwiftObjective-C
On the WWDC 2014, Apple once again unveiled the new programming language Swift. There was no leakage before the message. At the time the news was published, the Conference venue was stunned. I believe that coders who watched the live broadcast all over the world also felt that their heads were knocked on. So I stayed up late and learned the Swift method. The more I read it, the more I want to shout. "The Swift method is good! "
For programmers, the most important thing is to be realistic and objective. Next we will start to compare the two languages.
The first thing to emphasize is that Swift is definitely not an explanatory language, not a scripting language. Like Objective-C and C ++, the compiler will eventually translate it into C language, that is to say, the compiler is actually faced with C language code (this is really true and unquestionable !!! So don't look at it for a long script language. In fact, it is much more efficient than Java and C !!!), But Swift is powerful in that it stands on the shoulders of all languages and absorbs the essence of all languages.
In this series, let's talk about several basic syntax changes:
But Apple won't be so mediocre. We know that the syntax for method calling in Objective-C is not available in other mainstream languages, that is, labels. When we use java, C ++, C, C #, and other languages, if we use rect. set (10, 20,100,500), although the IDE prompts the meaning of the four parameters when writing the set method, after writing the code, what do the meaning of the 10 and 20,100,500 in the code mean? So the readability of the Code becomes very poor, and Objective-C perfectly solves this problem:
C code
[Rect setX: 10 y: 20 width: 100 height: 500]
[ rect setX:10 y:20 width:100 height:500 ]
Look! Great! Swift certainly won't discard such a good tradition. It looks like this in Swift.
C code
Rect. set (10, y: 20, width: 100, height: 500)
rect.set( 10, y:20, width:100, height:500 )
When calling a method, pay attention to the following two points for label usage:
1) You cannot use tags to call global functions.
2) For class functions, the first parameter cannot be tagged.
In fact, the definition of classes in Swift is almost the same as that in java and c #, regardless of header files and. m files.
The syntax for defining 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:: The statements in Swift do not need to end with a semicolon.
Second, there are finally constructor and destructor !!! Are there also Objective-C? No !!!
No constructor exists in Objective-C. The real constructor is automatically called by the system, rather than forcing programmers to call the constructor. I used to force the programmer [[Obj alloc] init]. Now the system has finally called it automatically!
C code
Weapon weapon = Weapon (name: "Human Cannon", power: 100000000000)
Weapon weapon = Weapon (name: "Human Cannon", power: 100000000000)
I am not wrong, right! Now it is the same as java and C! Although weapon is a pointer, do not write that asterisk !! This asterisk scared many people! "What? Pointer ?!! Ah ....."
C and C ++ programmers have noticed that this weapon object is not allocated to the stack memory, but also alloc, and is on the stack.
Override has problems in Java, C ++, and Objective-C. For example:
C code
@ Interface Weapon
-(Void) shoot;
@ End
@ Interface Gun: Weapon
-(Void) Shoot;
@ End
@interface Weapon-(void)shoot;@end@interface Gun : Weapon-(void)Shoot;@end
This problem is often encountered in large projects. The programmer's intention is to overwrite the shoot of the parent class, and the result is a boom .... If it is written as Shoot, there is neither a syntax error nor a logic error.
C code
Weapon * currentWeapon = [Gun new];
Weapon* currentWeapon = [ Gun new ];
In [currentWeapon shoot], the shoot method of the parent class is called (because the subclass is not covered at all, and the case of the subclass is accidentally incorrect ), this small error is hard to find if it appears in super-large projects !! Now, Swift has finally solved this problem! When a subclass overwrites the parent class method, override must be written before the method:
C code
Override func shoot {
}
override func shoot{}
In this way, the compiler will check whether there is a shoot method in the parent class when override is written before the method. If you write an error into override func Shoot, then the compiler will immediately find an error!
Series (II)
After Series 1 was published, some people disagree with my argument that # swift will replace objective-c #. Here I want to emphasize two points:
1) Swift is actually a text Variant of Objective-C. For this brand-new language, Apple's work is far from what we imagined. The LLVM compiler only translates swift into the Objctive-C code first, then the Objective-C code into the C language code, and then the C language code into a compilation, finally, it is translated into a machine code. As to why compiler vendors do not directly translate their own languages into assembler and machine code, it is because the existing language compilers (Objective-C, C) are very mature, the development and maintenance costs of text conversion between advanced languages are extremely low. Why does Swift translate it into Objective-C is because Swift still needs the ARC, GCD, and other environments constructed in Objective-C.
2) since the Swift code will eventually be translated into Objective-C by LLVM, what is the significance of the Swift language? Think about how we reacted when the ARC was just launched. Many people think that I am a senior objective-c Mazi, and I am well versed in memory management, [obj release] and [obj autoRelease] are not stop writing. Only beginners can use ARC. The result is less than a year. ARC ruled the entire Mazi community, because we should focus on business logic, rather than focusing on low-level questions such as syntax, the less time the syntax consumes, the more successful the language is.
Since Swift is actually Objective-C, it is far more studious to attackers than Objective-C, for senior developers, it can save a lot of unnecessary low-level repetitive mechanical Code (the code will be automatically written by the compiler when LLVM translates it into Objective-C ). I cannot think of any reason why Swift does not replace Objective-C.
Well, the argument is that we can see from the beginning how swift evolved.
1) The statement does not need to end with a semicolon, and the variable does not need to be of type if it is initialized.
C code
Var n = 22
var n = 22
For the compiler, since you initialize to 22, it certainly understands that n is an int and you press Enter. Of course, it knows that this is the end of the statement, therefore, LLVM translates it
C code
Int n = 22;
int n = 22;
Of course, there is no way for the compiler to put one row in multiple statements. You should use a semicolon to end the sentence. If Initialization is not performed, You can manually specify the variable type.
C code
Var n = 22; var hero: Hero
var n = 22; var hero:Hero
So it seems that there is no type variable, and it is actually a strong type (the compiler has done it for you ).
If it is a constant, use let
C code
Lets PI = 3.1415926
let PI = 3.1415926
Here, PI is a constant. Now, let PI = 3.1415926. PI is obviously a double. Why do programmers need to write a double ?!
2) Function Definition
C code
Func test (p1: int, p2: int)
{
}
func test( p1: int, p2: int ){}
Call: test (25,100) // Note: The global function is called, and the parameter cannot be tagged.
If a return value exists, the return type is represented 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) Class Definition
No more header files and m files! This is exactly the same as java and 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 )”; }}
Note that the constructor is available !! Init is automatically called by the system and does not need to be manually called by the programmer. Therefore, it is different from common functions. func cannot be added to the front. Why does the compiler do this? If init allows func to be added in front, the compiler will not know whether it is a constructor intended by the programmer if the programmer accidentally writes the init function name incorrectly and writes it as func Inot. Currently, no func is added before the constructor. If you write it as Inot (). The compiler does not know that you want to write the constructor before reading func, but the function name is not init. the compiler will know that you can immediately report an error if you accidentally make a mistake !!
4)#Optional variable# --- Difficulties encountered in all advanced languages
For example, the customer needs to provide a final API, and the customer needs to find the score of the student whose name is "jack. xu" in the data source. This api should be designed as follows:
C code
Int FindScoreByName (DataSource * source, string * name );
int FindScoreByName( DataSource* source, string* name );
The problem arises. If jack. xu does not exist, what should he return? Returns 0? That must be wrong, because 0 may also be the score of the student. Of course, if the returned object is a Class Object and NULL is directly returned, the caller will know that it is not found. Now it is a basic data type, and the returned NULL is actually 0. What should I do? (In c, C ++, the standard practice is to return bool to indicate whether to find the result, and pass the result through the form parameter. In other advanced languages, a small class/package class can be encapsulated)
Swift specifically designed a variable named "optional value (optional variable)" to solve this problem.
Syntax:
C code
Var n: UInt? = 5 or var n? = 5
Var n: UInt? = 5 or var n? = 5
Here? N indicates that n is an optional variable, that is, n may not exist. Under what circumstances does n not exist?
If you write:
C code
Var n: UInt?
var n : UInt ?
In swift syntax, nil is not 0, but a NilType variable.
So the problem mentioned above can be easily solved.
C code
Func FindScoreByName (source: DataSource, name: String)-> UInt? // Optional variables are returned.
{
Var score: UInt ?; // No memory is allocated for the score variable, that is, the score is nil.
If (source. HasStudent (name: name ))
Score = source [name]. score; // The score is allocated with memory;
Return score; // if no student information is found, the score memory is not allocated.
}
Func FindScoreByName (source: DataSource, name: String)-> UInt? // The returned result is an optional variable {var score: UInt ?; // No memory is allocated for the score variable, that is, the score is nil if (source. hasStudent (name: name) score = source [name]. score; // here the score is allocated with memory; return score; // if no student information is found, the score memory has not been allocated}
There is no need to learn objective-c when Apple launches Swift.
No, according to apple, Swift is superior to objective-c in all aspects. Since it is better, why do we need to learn Old and low performance?
The advantage of objective-c is maturity, but maturity cannot cover up its shortcomings. Although Swift is young, it may have great potential (whether it has great potential to develop with apple ), after all, it only applies to apple
If you focus on apple development, it is better to learn Swift directly. It is easy to learn one course first, even if needed. For the moment, Swift has few materials, but as long as you have the perseverance to learn, this should not be a problem. Besides, what can you worry about?
What is the difference between swift and objectiveC?
Of course it is object-oriented. Learn it now. After Apple throws swift, it gradually discards Objective-C.