Ios, ios9

Source: Internet
Author: User
Tags unpack

Ios, ios9

Swift syntax BASICS (II). If you want to learn swift, you can take it for reference. If you are interested, you can discuss and learn together. I. automatic Reference count 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 pointing to the object, the reference count of the object is + 1, the strong reference disappears, automatic count-1 1.3 if the reference count of an object is 0, the object will be destroyed. circular reference 2.1 What is a circular reference? Two or more objects strongly reference each other. What is the impact of circular references on the project? circular references will prevent objects from being destroyed and kept in the memory, may lead to poor project operation 2.3 how to solve the issue of strong reference? You only need to make the reference of one object to another weak reference. In swift, waek is equivalent to _ weak in OC, or unowned is equivalent to _ unsafe_unretained 3 in OC. difference between weak and unowned 3.1 similarities: both are weak references and do not retain objects 3.2 differences 3.21 weak (_ weak): When the objects pointed to by weak references are destroyed, this reference will point to nil. Therefore, the Data Type directed by weak is optional. The value is 3.22 unowned (_ unsafe_unretained). When the weak reference points to the object for destruction, it still points to the original memory address, error prone (wild pointer/access zombie object) 3.23 unowned does not support optional type 2. optional chain 1. what is an optional chain? Simply put, it is a chain composed of optional objects. 2. Why does it generate an optional chain? 2.1 suppose there are three categories: People, dogs, and toys. 2.2 people have the property of a dog. A dog has the property of a toy, there is a price in the toy. The property 2.3 assigns the toy object to the dog (let the dog own the toy), and assigns the toy object to people (let people own the dog) 2.4 if you want to change the price of toys by people, you need person. dog. toy. to modify the price of 2.5 person. the dog value type is optional, because the dog property of a person may be the nil property, and you want to use person. dog. You must forcibly unpack the package 2.6 person. dog. toy is also an optional type. In this way, the chain composed of optional objects is optional chain 3. optional chain Note: 3.1 when using the optional chain value, you must unpack 3.2 when using the optional chain value, do not forget to unpack 3.3 when using the optional chain call method, you must also first unpack 4. use the optional chain Value assignment, value, call method 4.1 to assign values to the optional chain:
1 person. dog !. Toy !. Price = 50 is too dangerous to forcibly unpack. if there is no value, the program crashes directly. 2 3 if let dog = person. dog {4 if let toy = dog. toy {5 toy. price = 506} This solution is safe, but it is too troublesome 7}
Apple recommends this method in swift to assign values to optional links.
1 person. dog ?. Toy ?. Price = 50 2 // when person. dog is nil, subsequent operations will not be executed
4.2 optional chain values: the value type extracted from the optional chain must be optional (may not be available)
let price = person.dog?.toy?.price
4.3 optional Trace call method: the system automatically determines whether the optional type has a value.
person.dog?.toy?.flying()
Iii. Protocol 1. How to define protocol methods and classes, struct, and enumeration similarity in Protocol 1.1 swift
Protocol SomeProtocol {// protocol method}
1.2 For example: Define a motion Protocol
1 protocol SportProtocol {2     func playBasketball()3     func playFootball()4 }
2. Declare a class and comply with protocol 2.1 to declare a base class (do not inherit other classes) and comply with the Protocol
1 class SomeClass: FirstProtocol, AnotherProtocol {2 // class content 3 // method in Implementation Protocol 4} 5 6 Example: 7 class Person: SportProtocol {8 var name: string = "" 9 10 func playBasketball () {11 print ("basketball") 12} 13 14 func playFootball () {15 print ("") 16} 17}
Class 2.2 inherits from other classes and complies with the Protocol
1 class SomeClass: SomeSuperClass, FirstProtocol, AnotherProtocol {2 // class content 3 // Method 4 in Implementation Protocol}
3. OC swift does not support multi-inheritance, but it can indirectly implement multi-inheritance through protocols. 4. Inheritance of Protocols. 4.1 The differences between swift and OC (NSObject) are: NSObjectProtocol
1 protocol CrazySportProtocol : NSObjectProtocol {2     func jumping()3 }
4.2 one agreement can comply with another agreement
1 protocol SportProtocol : CrazySportProtocol {2     func playBasketball()3 }
When a class complies with this Protocol (SportProtocol), it is equivalent to also complying with the CrazySportProtocol protocol. Therefore, the method 5 in the two protocols must be implemented. the Protocol 5.1 OC can be defined as optional and mandatory. By default, 5.2 is required. By default, all protocols in swift must be implemented, otherwise, the compiler will report an error 5.3. If @ objc is added before the Protocol to make the Protocol optional (not required) in swift, some features of OC can be retained, add optional before the method. This method is optional. When implementing the Protocol method, add @ objc before the method.
1 @ objc protocol SportProtocol {2 func playBasketball () 3 func playFootball () 4 // with optional, this method becomes optional 5 optional func jumping () 6} 7 8 class Person: SportProtocol {9 @ objc func playBasketball () {Add the keyword @ objc before the method, whether optional or required 10} 11 @ objc func playFootball () {12} 13 @ objc func jumping () {14} 15}

 

6. protocol use in proxy mode 6.1 generally, the protocol uses weak to modify (weak reference) 6.2 weak can only be used to modify the class 6.3 protocol in swift can be observed by class or struct, enumeration follows 6.4. How can we ensure that the Protocol is only followed by the protocol name by class? 4. closure 1. what is a closure? Closures are very similar to blocks in OC and are generally used for callback of functions. 2. block review block as the attribute format: '@ property (nonatomic, strong) void (^ finishedCallback) (NSString *)'; block as the Parameter Definition Format: '(void (^) (NSString * str) finishedcallback' 3. closure format: (parameter list)-> (Return Value Type) 4. use of closures

 

5. Trailing Closure
1 // trailing closure: if the last parameter of a function is a closure. so we can write the function call into the trailing closure 2 // is to write the closure to the end of (), which is originally written in 3 tools in ?. LoadData () {(result) in 4 print ("Get data in ViewController: \ (result)") 5} 6 7 // if the function has only one parameter, and it is a closure, so () can also omit 8 tools ?. LoadData {(result) in 9 print ("Get data in ViewController: \ (result)") 10}

 

6. circular reference of the closure 6.1 when defining the tool class, it will be used in the tool class method 6.2 When the tool class has a strong reference to the closure, a controller calls the method containing the closure, when the Controller attribute is used in the closure method, a circular reference of the 6.3 controller call method will occur, and a strong reference will be made to the tool class, and the closure will get the Controller attribute, the closure object has a strong reference to the Controller. 6.4 is equivalent to this performance in the memory.

 

7. How to Solve the circular reference of closure and the type in oc, and change the reference of closure to controller to weak reference 8. How to change it? When the closure modifies the Controller attributes and obtains the Controller attributes, change self (Controller) to weakself to weak var weakself: ViewController? = Self 5. description of the directory structure of the swift project 1. the swift project directory does not exist. h and. m file, only one. swift files, equivalent to 2. in the swift directory. the swift file is equivalent to. h and. m file 3. in swift, other source files in the call Project do not need to be imported into the header file (one. the swift file is a source file.) 6. lazy loading 1. the introduction of lazy loading is different from that in OC 1.1. swift has special keywords to implement lazy loading. The essence of lazy loading is that it is loaded only once when used for the first time. the lazy keyword is used in swift to implement lazy loading of 2.1 lazy loading formats.
Lazy var variable: TYPE = {create variable code }()
= The following is a closure. We recommend that you use a closure to implement lazy loading. You can initialize the variable attributes in the closure. 2.2 lazy loading is used.
1 lazy var names : [String] = {2   return ["why", "yz", "lmj"]3 }()

When the above code is executed, names will not be loaded into the memory. When names is used for the first time, it will be loaded.

No matter how many times the names is used, it will only be loaded once, that is, there is only one names attribute address in the memory. common notes in swift 1. use the same single-line comment as the single-line comment in OC // comment content 2. the format of Multiline comments is the same as that of multi-line comments in OC./* Comment content */different, multiple comments in swift can be nested. 3. document comments are different from those in oc. In swift, you can use // comments to annotate documents. 4. the Group comment is different from the oc: # pragma mark-Comment content swift: // MARK:-Comment content 8. access permission 1. internal: internal 1.1 when no specific access permission is specified, the default access permission is internal 1.2 internal: access is allowed anywhere in the current project (package. private: the access permission of private: You can access one in the current source file. swift file is a source file 3. public: public 3.1 public access permission: The concept that cross-package access is allowed: a project or a framework, UIKit, is also a framework 9. exception Handling 1. in swift, if there is a throws at the end of a method, this method can throw an exception Regular Expression and throw an exception: NSRegularExpression (pattern: <# T ## String #>, options: <# T # NSRegularExpressionOptions #>) 2. if a method throws an exception, you must handle the exception. Otherwise, the compilation reports an error. 3. three methods for exception handling: 3.1 try: manually handle the exception, you can get the exception (error). Add try before the method and use do to wrap it out.
// Try Method --> manually handle exceptions and obtain the final exception result do {// if there is an exception error, the value of let regex = try NSRegularExpression (pattern :"", options :. caseInsensitive)} catch {// get the exception result print (error) Through error )}

 

3.2 try? : System Exception Handling. try? Method: if an exception exists, nil is returned. If no exception exists, the returned result (regex) is of the optional type. let regex = try? NSRegularExpression (pattern: "", options:. CaseInsensitive) regex ?. MatchesInString ("", options: [], range: NSMakeRange (0, 0) 3.3 try! : Tell the system that there may be exceptions. try! Method (not recommended) Note: once an exception occurs, the program will crash. let regex = try! NSRegularExpression (pattern: "", options :. caseInsensitive) 10. how to throw an exception 1. if throws is added after the method parameter, the return value must be 2. in some specific situations, an exception is thrown, for example, the passed parameter is incorrect. Internally, the parameter must be determined. 3. the thrown exception is generally defined as an enumeration type that must be later than ErrorType.

 

11. OC and swift call each other. swift calls oc 1.1 to create a bridge file (. h file) the file name is generally Bridge. h 1.2 import the oc header file in the Bridge file 1.3 configure the Bridge File Project-> BuildSetting-> Search for bridging and write it to the Bridge. relative Path of h

 

2. the name of the swift 2.1 project called in oc must be standardized (Chinese characters and special characters are not allowed). The class and attribute in swift 2.2 should be specified, before the method name, add public 2.3 to import the project name to the oc file-Swift. h header file project name-Swift. the h system automatically generates

 

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.