"Learn Swift from Scratch" Study Notes (Day 58) - Variable or Constant Declaration Specifications of Swift Coding Specifications

Original article, welcome to reprint. Please indicate: Guan Dongsheng's blog

 

A declaration is a specification that needs to be followed when declaring variables, constants, properties, methods or functions, and custom types.

First of all, when declaring variables or constants, it is recommended to declare one variable or constant per line, because it is convenient for writing comments. The sample code is as follows.

Recommended Use:

let level = 0
var size = 10

 

Deprecated:

let level = 0; var size = 10

 

The data type of the variable or constant , if possible, should use type inference as much as possible, so that the code is very concise. The sample code is as follows.

Recommended Use:

let level = 0
var size = 10

 

Deprecated:

let level: Int = 0
var size: Int = 10

 

If it is not the default data type, you need to explicitly declare the data type of the variable or constant. The sample code is as follows.

let level: Int8 = 0
var size: Int64 = 10

 

When specifying the data type, you need to use a colon ( : ), there should be no space between the size and the colon, and there should be a space between the colon and the data type. The sample code is as follows.

Recommended Use:

let level: Int8 = 0
var size: Int64 = 10

 

Deprecated:

let level : Int8 = 0
var size:Int64 = 10

 

When using data types, use Swift's native data types as much as possible, for example:

Recommended Use:

let width = 120.0
let widthString = "Hello."
var deviceModels: [String]
var employees: [Int: String]

 

Deprecated:

let width: NSNumber = 120.0
let widthString: NSString  = "Hello."
var deviceModels: NSArray
var employees: NSDictionary

 

property declaration

Properties include stored properties and computed properties. If it is a stored property, the declaration specification is the same as that of a variable or constant declaration. If the computed property is similar to a code block, omit the get statement if possible when using read-only computed properties . The sample code is as follows.

Recommended Use:

var fullName : String {
    return firstName + "." + lastName
}

 

Deprecated:

var fullName : String {
    get {
        return firstName + "." + lastName
    }
}
 

 

 

 

 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327042874&siteId=291194637