Swift essentials: See Swift from the perspective of OBJECTIVE-C developers

Source: Internet
Author: User



The code environment is XCODE6.3-BETA3.



Swift has dramatically changed the way iOS apps are developed. In this article, I'll list some of the highlights of swift and compare it with objective-c one by one.



Note that this article is not an introductory guide to Swift. Apple has released Swift programming Language, and it is highly recommended that you read this book. The text mainly describes the cool features of Swift.


Type


The first major improvement provided by Swift is type inference. Using the type inference programming language, the developer does not need to explicitly specify the type of the variable in the declaration. The compiler will automatically detect the type of value to assign to the variable. For example, the compiler automatically sets the type of the variable to string:


// type inference
var str = "Hello World!"

// Clearly define the type, this may not be the case here
var swift: String = "Hello Swift" 


and type inference are all about type safety. In Swift, the compiler (in general, but in rare cases) knows all types of a type. This gives the compiler an opportunity to choose how to compile the code, because the compiler has enough information.



This is supporting a very dynamic nature of the objective-c. In Objective-c, any type is unknown during compilation. That's why you can add methods to existing classes at run time, add a whole new type, and even change the type of an object.



Look at the OBJECTIVE-C code:


Person *man = [[Person alloc] init];[ Man SayHello];


When the compiler sees a call to the method SayHello, it checks to see if there is a method called SayHello in the header file of the type person class. If not, error. The compiler can only do this. This can really be the first simple bug you might introduce: such as spelling mistakes. However, because of the dynamics, it is impossible for the compiler to know whether the SayHello method will change in operation or even exist. This may be a optional method in a protocol. For example (remember those checks that use respondstoselector).



Because of the lack of strong typing, the compiler can hardly optimize when calling methods in Objective-c. The method for handling code dynamic distribution is: Objc_msgsend. I'm sure you've seen this way in a lot of times. In this method, look for selector and call. You cannot say that this does not add complexity.



Then look back at the implementation of Swift:


var p = person () P.sayhello ()


In Swift, the compiler knows more about the type when it calls the method. It knows exactly where the Sayhell method is defined. Therefore, Swift can switch directly to the method definition at the time of the method invocation without having to go through any dynamic distribution processes. In other cases, Swift can also use the vtable-style distribution method, which is much less expensive than OBJECTIVE-C's dynamic distribution. This is also the distribution mechanism used by the virtual method of C + +.



Swift's compilers are also very useful. You can exclude minor type-related bugs. It can also make your code run faster.


generic type


Another big change that Swift brings is generics. If you are familiar with C + + flowers, then you can compare these with C + + template. Because Swift is type-strict, you must approach the type of parameter that can be accepted. But sometimes your methods work the same for different types.



For example, you want to store a pair of values together. You can use Swift to implement a structure that holds integer values:


struct IntPair {
    let a: Int!
    let b: Int!
    
    init(a: Int, b: Int){
        self.a = a
        self.b = b
    }
    
    func equal() -> Bool { return a == b
    }
}

let intPair = IntPair(a: 1, b: 1)
println("\(intPair.a)" + "\(intPair.b)" + " equal: \(intPair,equal())")


Sort of useful. But now you want this to work for floating point numbers as well. You could define aFloatPairclass, and that's would look awfully similar. This is where the generics come in. Instead of declaring a whole new class, you could simply does this:



It's useful, but you want this to be used in floating-point numbers, too. You can define a Floatpair class, but it's just too similar. Generics will be useful at this time. As opposed to defining a completely new type, you can do this:


struct Pair<T: Equatable> {
    let a: T!
    let b: T!
    
    init(a: T, b: T){
        self.a = a
        self.b = b
    }
    
    func equal() -> Bool { return a == b
    }
}

let tempPair = Pair<Int>(a: 1, b: 1)
var tempA = tempPair.a
var tempB = tempPair.b
var tempEqual: Bool = tempPair.equal()

println("\(tempA) " + "\(tempB) " + "equal: \(tempEqual)")

let tempPair1 = Pair<Float>(a: 1.0, b: 1.0)
var tempA1 = tempPair1.a
var tempB1 = tempPair1.b
var tempEqual1: Bool = tempPair.equal()

println("\(tempA1) " + "\(tempB1) " + "equal: \(tempEqual1)")

I beg your readers to forgive me for using such a rotten way of naming ah ...


Very useful! You may not be quite sure why you need generics, but trust me there will be a lot of times you will use them. You'll soon find out where you can use the code.


Container


Maybe you think Nsarray and Nsdictionary and the corresponding mutable types are already very useful. But you need to learn the corresponding Swift container. Fortunately, they are very similar. Such as:


Let array = [1, 2, 3, 4, 5= ["dog""elephant": 2]


These are very familiar to you. Take a look and you can fix it. In objective-c, arrays and dictionaries can contain any type you want. However, in swift, arrays and dictionaries are strongly typed. And these containers are generic types.



The above two variables can be overridden using type expressions (you don't have to do this), such as:


Let array:array<int> = [1, 2, 3, 4, 5]let dictionary:dictionary<string, int> = ["dog
    ""elephant": 2]


Notice How generics is used to define what can is stored in the container. There is also a short form for these, which are slightly more readable, but essentially boils down to the same thing:



Notice how generics define what can be put into a container. The way you define it is also available in a short way, with better readability. But it's essentially the same:


Let array: [Int] = [1, 2, 3, 4, 5= ["dog""elephant": 2]


Note that you cannot add any values to the array that are not of type int at this time. It doesn't look good, but it's very useful. You no longer need to specifically indicate in your document what type of value is stored in the array returned by the property. The compiler automatically detects errors and optimizes the compilation of the code.


Variability


One of the interesting parts of Swift containers is that they are all mutable (mutable). The array and dictionary do not have the corresponding type of "mutable". Both mutable and immutable are controlled by the Let and var keywords. Let is the keyword used to declare a constant, and VAR is used to declare a variable. Let is like the const keyword in C, C + +, or objective-c.



The the-the-relates to collections-is-collections declared usingletcannot change size. That's, they cannot be appended to, or removed from. If you try to and then you get a error like so:



A set that uses a let declaration can no longer modify size, that is, no longer append or remove. If you do this, you will get an error:


Let array: [int] = [1, 2, 3, 4, 5]array.append (+)'[int]'  Append'


The same rule is used in dictionaries. This allows the compiler to infer this type of collection and make the appropriate optimizations. If size cannot be modified, the storage implementation of the collection no longer needs to reallocate new space to accommodate the new value. Therefore, it is a good practice to often use let to define collections that are no longer changing.


String


Objective-c strings are very difficult to use. Even a simple concatenation of strings is a lot of code to write. Like what:


Person *person = ...;
 
NSMutableString *description = [[NSMutableString alloc] init];
[description appendFormat:@"%@ is %i years old.", person.name, person.age]; if (person.employer) {
  [description appendFormat:@" They work for %@.", person.employer];
} else {
  [description appendString:@" They are unemployed."];
}


This was quite tedious and contains a lot of characters so is nothing to do with the data being manipulated. The same in Swift would:



The notation is lengthy and contains other characters that are not relevant to this operation. The same function looks like this in swift:


var description = "" description += "\(person.name) is \(person.age) years old." if person.employer {
    description += " They work for \(person.employer)." } else {
    description += " They are unemployed." }


It's very clear. To create a more clear string, you can use the string concatenation operator + =. Mutable strings and non-mutable strings are no longer required.



Another swift string change is "string comparison". You know that you can't use = = to compare the equality of two strings in a objective-c. You have to use the Isequaltostring method. This is what should be = = is the comparison of whether the pointers are equal. You can use = = to compare two strings directly in Swift. That is, the string can be in an switch-case expression. For more information, please continue with the next section.



Another good thing about Swift's string is that Unicode is natively supported. You can use any Unicode character, even in the variable name and function name. You can declare a method if you want.



Swift essentials: See Swift from the perspective of OBJECTIVE-C developers


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.