Remember OC migration to Swift in note 20tips

Source: Internet
Author: User
Tags instance method unpack try catch

after writing for a long time, OC later wrote Swift, always feeling that it was Swift's fur, but in fact it was the core of OC, where some of the small details of OC migration to Swift were collated.

1 in the current class, the instance method invocation properties and methods all can omit self, and it is recommended to omit

2 Selector is the method of invocation: Selector ("SayHello") or #selector (SayHello)

3 There is no direct operation between the different types of values in swift, so different types of values need to be converted to the same type before the operation can be performed.

4 可选类型 If a variable may have a value or be empty, then this variable is an optional type. Optional types are added after the variable's data type ? , such asvar str:String?

1 The value of the optional type cannot be directly involved in the operation, it needs to be forcibly unpacked before it can be used, using '! ` 2 identifies a value that forcibly unpacked an optional type. Use '! ' Be sure that the value is not ' nil ' to 3 to force unpack this value, if the ' nil ' is forced to unpack the program will crash


5 Control Flow

    • if--let

      if-let is generally used to determine the optional type variable if let n =    name{//  When name has a value it will set a constant N to record the value of the optional type at this time     and be able to enter into the Judgment statement code block}

如果变量name没有值的话继续往下面执行
    • if-let-where

      if-let-where usage is similar to if-let, one more judgment 1where is to add a judgment to the previously defined constants (where  True/false)2If let changes the defined constants (which actually need to be changed to variables), just change the let to Var.

    • guard
Guard than if-varelse{        When the value of the variable m is empty, execute the code block here, and return to the end after execution        ...         . return } do not empty words down execute printf (n)

6 switch

    • Do not write break does not create a cross-cutting phenomenon, so break can not write

    • Case can judge any type (including string, etc.), no longer like OC can only judge the integer type

    • The scope of the specified variable is not written in the case {} , but execution code is required after each

7 Required and optional properties

    • Required properties need to have values before object initialization is complete

    • If you are assigning a value to a constructor before it is initialized, you must super.init() precede the

    • The default value is nil if the base data type is an optional type

8 Swift refines the type of the attribute

    • 存储类型Variables and constants that store instances, related to classes, structs, enumerations

    • 计算属性Instead of storing the actual value, the value of the property is indirectly obtained and set through a setter and getter method

    • 类型属性Type properties are related to classes, not instances, and for instances of a type, type attributes have only one copy, and type properties can only be obtained and manipulated by type

9 Set method and get method

  • Swift does not rewrite the set and get methods like OC
  • Set method notation

    var variable name: variable type? {          didset{              set content          }      }

  • Lazy loading is get方法 recommended for swift, and lazy loading in Swift has a fixed notation

    var variable name: Variable type = {// lazy Loading must indicate variable type       creation variable ...      .       return variable  } ()

  • Manual implementation of variables set and get methods

    var variable name: variable type? {      didset{          the contents of the Set      method      }get{          return  ...      }  }

10 Overriding init(frame:CGRect) Methods

    • In Swift, the UIView init (Frame:cgrect) method must be rewritten as long as it is rewritten init?(coder aDecoder: NSCoder) . Otherwise, the error is due to the use of pure code rewrite the Init method, in the future Code iterations may be used xib, when the use of Xib method will execute the init?(coder aDecoder: NSCoder) method

Single example in Swift

    • Swift's single-instance method does not suggest the use of OC's singleton idea, and Swift's single-case notation
static let singleinstance: class name = {        = class name ()        return  instance    } () or     static Let instance = class name ()    = {          return  Instance    }

When iterating through an array in swift, you must specify the type of elements inside the array

   for inch as! [String:anyobject]    {    }

13 dynamically creating class instances based on strings:

In Swift, when an instance of a class is initialized, the class name is preceded by a namespace and then initialized, so creating an instance based on a class name string requires first obtaining the class name space

    • In Swift, the composition of the class name isnameSpace.类名
    • Namespaces nameSpace are typically project names, which can be obtained by:
      namespace = Nsbundle.mainbundle (). infodictionary! ["cfbundleexecutable"as! String

14 Exception capture Try Throw

    • The try catch is handled incorrectly by SWIFT, and errors must be handled as long as there is an error parameter

       Do {      try    }catch{      Executes the code inside the catch when an error is thrown  }   // if it is a strong try (try!), then the exception throws the words directly crashes, and does not jump into the catch inside

CGRectOffsetUse of

```    //第一个参数:frame大小    //第二个参数:x方向偏移的大小    //第三个参数:y方法偏移的大小 CGRectOffset(frame,x,y)```

16 button listener cannot use private adornments

    • Methods that are used only in this class should be private decorated to improve the readability of the code to some extent
    • The button's listener cannot use private adornments, because the button's listener is invoked by Runloop, not by this class, so the program crashes when the button's listener is used private to decorate.

17 The closure callback should receive a optional type, not used , is forced to unpack, when the closure callback if there is a parameter of nil, the use of ! forced unpacking will cause the program to crash

Dictionary-to-model in Swift

Init (dict) {        super.init ()        setvaluesforkeywithdictionary (dict)    }

In Swift, you can directly modify the variables inside the struct by using dot syntax

    • Like directly modifying the X value inside the frame.
    0

Use of compliance agreements in Swift

    • Use the form of classification
    extension 本类名:协议名    {    }

Remember OC migration to Swift in note 20tips

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.