Swift Learning (iv)

Source: Internet
Author: User

5. Enumerations and structs:

You do not have to provide a value to an enumeration member. If we want to provide an enumeration member with a value (raw value), we can use a string, character, integer, or floating-point number type.

1234567 enum CompassPoint {caseNorthcase Southcase Eastcase West  }  vardirectionToHead = CompassPoint.West
    • Structural body

Structs in swift and classes have many of the same places, you can define attributes, methods, initialization methods, which can be extended by extension, and so on.

The difference is that a struct is a value type. In the process of passing through a copy.

It is mentioned here that the first section above mentions the String,array and dictionary in Swift as a value type. The reason behind this is that String,array,dictionary is implemented through structs in Swift. Before Objective-c, they were all implemented by class.

The powerful structs in swift allow us to deal more with value types. The value type of Swift enhances immutability (immutabiliity). And immutability improves the stability of our code and the security of multithreading concurrency.

6. Agreement (Protocols)

protocol SampleProtocol {    func someMethod()}

Following the agreement in Swift:

1234 class AnotherClass: SomeSuperClass, SampleProtocol{    func someMethod() {}}

The current pure Swift protocol does not yet support optional. But in response to an employee at Apple's official forum, Swift will support the future.

Protocol and delegate are closely linked. So how do we define delegate in Swift?

12345 protocol MyDelegate : class {}class MyClass {    weak vardelegate : MyDelegate?}

Notice the class that follows the protocol definition above. This means that the protocol can only be adhered to by the class type.

And only delegate with class protocol can be defined as weak. This is because in swift, in addition to class being able to comply with the protocol, enumerations and structs can also comply with the protocol. While enumerations and structs are value types, there is no memory management problem. It is therefore only necessary to declare a variable of class type as weak.

With Swift's optional chaining, we can easily check if the delegate is nil, and if there is a way to implement it:

We used to check this in objective-c:

123  if(self.dataSource && [self.dataSource respondsToSelector:@selector(titleForSegmentAtIndex:)]) {        thisSegmentTitle = [self.dataSource titleForSegmentAtIndex:index];    }

In Swift, it's very elegant and concise.

12 iflet thisSementTitle = dataSource?.titleFroSegmentAtIndex?(index){}

New features:

1. In swift, protocol becomes more powerful and flexible:

2.class,enum,structure can abide by the agreement.

Extension can also abide by the agreement. With it, we don't need to inherit, we can also let the class of the system follow our protocol.

For example:

12345678 protocol myProtocol { func hello() -> String}extension String:myProtocol{ func hello() -> String {     return"hello world!" }}

We can also use this feature to organize our code structure, as shown in the following code, to move the implementation of Uitableviewdatasource to extension. Make the code clearer.

1234 // MARK: - UITableViewDataSourceextension MyViewcontroller: UITableViewDataSource {// table view data source methods}

3.Protocol Oriented Programming

With the release of Swift2.0, protocol-oriented programming was formally added to the swift programming paradigm. Cool.

How does this programming approach be supported by the grammatical characteristics?

That is, we can extend the protocol, that is, we can provide the default implementation of the Protocol, can add new methods and implementations for the protocol.

Using the previous MyProtocol as an example, we provide it with a default implementation in Swift.

12345 extension myProtocol{    func hello() -> String {     return"hello world!"    }}

We can also extend the original protocol of the system, greatly enhancing our imagination space. The implementation of Swift2.0 has also been reconstructed in many places in the form of extension protocol.

7.Swift and Cocoa

The strength of a language, in addition to its own excellent characteristics, is a big bit of the framework behind it. Swift uses Apple's long-running cocoa framework directly. Now let's look at some of the things you need to be aware of with swift and cocoa interactions.

    • ID and Anyobject

In Swift, there is no ID type, and Swift uses a protocol named Anyobject to represent any type of object.

1  id myObject = [[UITableViewCell alloc]init];
1  varmyObject: AnyObject = UITableViewCell()

We know that the type of ID is not determined until run time, and if we send an unresponsive message to an object, it causes crash.

We can use Swift's syntax features to prevent such errors:

1 myObject.method?()

If MyObject does not have this method, it will not execute, similar to checking whether delegate has implemented the proxy method.

In Swift, the property acquired on Anyobject is optional.

    • Closed Package

Block in OC seamlessly converts to closures in swift. The function is actually a special kind of closure.

    • Error handling

Previous OC Typical error handling steps:

1234567 NSFileManager *fileManager = [NSFileManager defaultManager];NSURL *URL = [NSURL fileURLWithPath:@"/path/to/file"];NSError *error = nil;BOOL success = [fileManager removeItemAtURL:URL error:&error];if(!success) { NSLog(@"Error: %@", error.domain);}

In Swift:

1234567 let filemanager = nsfilemanager.defaultmanager () let url = nsurl.fileurlwithpath ( "/path/to /file " ) do  {   try   Filemanager.removeitematurl (URL) }  catch  let error as nserror {   print ( "error: \ (error.domain)" Code class= "JS plain") }
    • KVO

Swift supports KVO. But kvo in Swift, the individual feels is not graceful enough, KVO in Swift only supports inheriting NSObject class, has its limitation.

KVO has the ability to bind in OS X, that is, we can tie two attributes together, one property changes, and the other property changes. is helpful for synchronizing updates with the UI and data, and is one of the requirements of the MVVM architecture. This feature has been envious for a long time, and Swift's support for generic programming brings many new ideas to the open source world, although Swift does not natively support it.

Swift Learning (iv)

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.