iOS--teach you how to easily learn Swift grammar (iii) end of article

Source: Internet
Author: User
Tags unpack

I. Automatic reference counting 1. Automatic reference counting mechanism      1.1 swift and OC, use automatic reference counting to manage memory      1.2 when there is a strong reference to the object, the reference count of the object is +1, the strong reference disappears, Auto Count -1     1.3 If the object has a reference count of 0, the object is destroyed  2. Circular references      2.1 What is a circular reference?     &NB sp;     two (or more) objects with each other strong references       2.2 Circular references affect the project           Circular references keep objects from being destroyed, kept in memory, and can cause projects to run poorly           2.3 How to resolve strong reference issues?          Just make one of the objects reference to another object a weak reference,           use Waek in Swift as the __weak in OC, or use unowned equivalent to __u in OC The difference between Nsafe_unretained 3.weak and unowned      3.1 same point:            is a weak reference and does not retain  the object         3.2 the different points           3.21 Weak (__ Weak): When a weak reference is directed to an object that is destroyed, the reference points to nil   so the data type pointed to by weak is optional type           3.22 unowned (__unsafe_ unretained): When the object that the weak reference points to is destroyed, it still points to the original memory address, prone to errors (wild pointer/Access zombie object) &nbsp         3.23 unowned does not support optional types  two. Optional chain1. What is an optional chain?     Simply put, it is an optional type of object consisting of a chain 2. Why is an optional chain generated? 2.1 Fake There are three categories, people, dogs, toys 2.2 people have a dog this attribute, the dog has a toy this property, the toy has the price of this property 2.3 The object of the toy to the dog (let the dog own toys), the dog is assigned to a person (let the dog) 2.4 want to To change the price of a toy by a person, you need to person.dog.toy.price to modify the 2.5 Person.dog This is an optional type, because the Human dog attribute may be the nil attribute, and if you want to use Person.dog, you must force unpacking 2. 6 Person.dog.toy is also an optional type, and a chain of objects of an optional type, such as this one, is an optional chain 3. Optional Chain Note 3.1 When you use an optional chain to assign a value, be sure to unpack the 3.2. Do not forget to unpack the 3.3 using an optional chain You have to unpack the package 4 when you use the method. Use optional chain assignment, value, call method 4.1 to the optional chain assignment:
1   - too dangerous  to force unpack, if not value, direct program crashes 2  3 if let dog = person.dog {4     if let toy = Dog.toy {5 c15/>6    }  Such unpacking is safe, but too troublesome 7 }
In Swift, Apple recommends using this method to assign a value to an optional chain.
1  - 2 // when Person.dog is nil, the subsequent operation is no longer executed .
4.2 value from an optional chain: a worthwhile type that is removed from an optional chain must be an optional type (it may not be available)
Let Price = Person.dog?. Toy?. Price
4.3 Optional Chain call method: The system automatically determines whether an optional type has a value
Person.dog?. Toy?. Flying ()
three. Agreement1. How to define the Protocol 1.1 Swift in the way and class, struct, enum similar
protocol Someprotocol {    //  protocol method }
1.2 Example: Define a motion protocol
1 protocol Sportprotocol {2    func playbasketball ()3    func playfootball ()4 }
2. Declaring a class and complying with protocol 2.1 declares a base class (does not inherit other classes) and adheres to the Protocol
1 classSomeclass:firstprotocol,anotherprotocol {2     //the contents of the class3     //implementing the methods in the Protocol4 }5  6 For example:7 classPerson:sportprotocol {8     varName:string =""9    Ten func Playbasketball () { OnePrint"Play Basketball") A     } -     - func Playfootball () { thePrint"play football") -     } -}
Class 2.2 inherits from other classes and adheres to the Protocol
1 class Someclass:somesuperclass, Firstprotocol,anotherprotocol {2     // the contents of the class 3     // implementing the methods in the Protocol 4 }
3.OC Swift does not support multiple inheritance, but can be implemented indirectly through the protocol, multiple inheritance 4. The inheritance of the agreement 4.1 in swift and in the Protocol and OC (NSObject), the difference is: Nsobjectprotocol
1 protocol Crazysportprotocol:nsobjectprotocol {2    func jumping ()3 }
4.2 One protocol that can comply with another protocol
1 protocol Sportprotocol:crazysportprotocol {2    func playbasketball ()3 }
When a class complies with this Protocol (SPORTPROTOCOL) is equivalent to the CRAZYSPORTPROTOCOL protocol, it is necessary to implement method 5 in both protocols. Protocol Optional 5.1 OC protocol can be defined as optional and required, default is required 5.2 By default, the protocol in Swift must be implemented, otherwise the compiler will give an error 5.3 How to make the Protocol optional in Swift (without having to do it) to add @objc before the protocol, you can preserve some of the OC features, and optional the method before the method is available The choice is to implement the Protocol method, in front of the method also to add @objc
1 @objc protocol Sportprotocol {2 func playbasketball ()3 func playfootball ()4   //Add optional the method becomes optional.5 optional func jumping ()6 }7  8 classPerson:sportprotocol {9 @objc func playbasketball () {keyword @objc is also added before the method, whether optional or requiredTen     }  One @objc func Playfootball () { A     }  - @objc func jumping () { -     } the}

6. Use of the protocol in Proxy mode 6.1 in general, the Protocol is modified with weak (weak reference) 6.2 Weak can only be used to modify class 6.3 in Swift, the protocol can be either class-compliant, or struct, enumeration compliance 6.4 How to let the protocol only The class is followed by the protocol name plus: classfour. Closures1. What is a closure? Closures are very similar to blocks in OC, and are generally used to recall the function's callback 2.block in the format of the block as a property: ' @property (nonatomic, strong) void (^finishedcallback) (NSString     *)`; Block as a parameter definition format: ' (void (^) (NSString * str)) Finishedcallback ' 3. Closure format: (parameter list)--(return value type) 4. Use of closures

5. Trailing closures
1  //trailing closures: If the last parameter of the function is a closure. You can write a function call as a trailing closure2  //is to write the closure to the back of (), which is written in ()3Tools?. LoadData () {(result)inch4Print"data obtained in Viewcontroller: \ (Result)")5  }6        7  //If the function has only one parameter and is a closure, then () can also omit8Tools?. LoadData {(Result)inch9Print"data obtained in Viewcontroller: \ (Result)")Ten}

6. Closure of the circular reference 6.1 when defining the tool class, will be used in the tool class method of closure 6.2 when the tool class has a strong reference to the closure, a controller calls the method containing the closure, in the closure method using the controller's properties, a circular reference to the 6.3 controller call method, Will have a strong reference to the tool class, the closure and the controller's properties, the closure object to the controller has a strong reference 6.4 in memory equivalent to this performance

7. How to solve the loop reference of the closure and the type of OC, only need to change the closure of the controller reference to weak reference 8. How to change? When a closure modifies the properties of the controller, when it gets the properties of the controller, the self (Controller) is changed to Weakself to weak var weakself:viewcontroller? = SelfFive. Introduction to the directory structure of SWIFT projectsThere are no. h and. m files in the 1.swift project directory, and only one. Swift file is equivalent to the 2.swift directory. The swift file is equivalent to the. h and. m files in OC 3. In Swift, the other source files in the calling project do not need to be imported into the header file (one. Swift file is a source file)Six. Lazy Loading1. Lazy Loading Introduction 1.1 and OC in different, Swift has a special keyword to implement lazy loading 1.2 lazy loading essence: When the first use of the reload, and will only be loaded once 2.swift with the Lazy keyword to implement lazy loading 2.1 lazy loading format
var variable: type = {Create variable code} ()
= followed by a closure Apple recommends a closure for lazy loading, which initializes variable properties in closures 2.2 lazy load usage
1 var names: [String] = {2   return [" Why"] YZ " " LMJ " ]3 } ()

When executed to the above code, names will not be loaded into memory and will be loaded when names is first used

No matter how many times the names is used, it will only be loaded once, meaning there is only one names attribute address in memorySeven. Common annotations in Swift1. Single-line comments and single-line comments in OC Use//comment content 2. Multiline comments are the same as the multi-line comment format in OC */comment content */Different, a multiline comment in Swift can be nested using 3. Document comments are not the same as in OC , Swift uses the///comment content to implement the documentation notes 4. Grouping comments is not the same as OC OC: #pragma mark-comment content Swift://mark:-Comment contentEight. Access Rights1.internal: Internal 1.1 when no specific access rights are specified, the default is internal 1.2 internal: access to 2.private anywhere in the current project (package): Private privately access : The ability to access a. Swift file in the current source file is a source file 3.public: Public access to 3.1: The concept of 3.2 packages can be accessed across packages: either a project or a framework Uikit is also a frameworkNine. Exception Handling1. In Swift, if there is a throws at the end of a method, then this method can throw an exception to the regular expression: nsregularexpression (pattern: < #T # #String #>, Options: &          lt; #T # #NSRegularExpressionOptions #>) 2. If a method throws an exception, the exception must be handled, otherwise the compilation error 3. Three ways of exception handling 3.1 Try: Handle exceptions manually, you can get an exception (error) To add a try to the front of the method and to use do packing outside
      Try mode- -handles the exception manually and can get to the final exception      result do   {    //If there is an exception            error value try" ", Options:. caseinsensitive)      catch  {     //error to get exception result           print (Error)      }

3.2 try? : System handling Exception try? Mode: If there is an exception, returns nil if there is no exception, then the result result (regex) is the optional type let regex = try? Nsregularexpression (Pattern: "", Options:. caseinsensitive) regex? Matchesinstring ("", Options: [], Range:nsmakerange (0, 0)) 3.3 try!: Tell the system there can be no abnormal try! way (not recommended) Note: In the event of an exception, the program Will crash let regex = try! Nsregularexpression (Pattern: "", Options:. caseinsensitive)10. How to throw an exception1. After adding throws to the method parameter, be sure to have a return value of 2. Throws an exception in some specific cases such as: pass the parameter is wrong and so on, internal to the parameter to Judge 3. Thrown exceptions, which are generally defined as enumeration type enumerations followed by ErrorType this type

11. OC and Swift call each otherCall OC 1.1 in 1.swift to create a bridge file (. h file) file name is typically Bridge.h 1.2 import OC header file in Bridge file 1.3 configuration bridging file Engineering, BUILDSETTING-&GT ; Search bridging relative path to write Bridge.h later

Call the SWIFT 2.1 project name in 2.OC to specification (cannot have Chinese and special characters) 2.2 Swift class, property, method name before adding public 2.3 in OC file Import project name-swift.h header file Project name-swi The ft.h system will automatically generate

iOS--teach you how to easily learn Swift grammar (iii) end of article

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.