当前位置:网站首页>[swift] learning notes (I) -- familiar with basic data types, coding styles, tuples, propositions

[swift] learning notes (I) -- familiar with basic data types, coding styles, tuples, propositions

2022-07-07 03:11:00 Full stack programmer webmaster

Hello everyone , I meet you again , I'm the king of the whole stack

Since Apple announced swift after , I've always wanted to know , He has not been able to put it formally Study , Starting today , I will use my blog to drive swift hear , As far as we know, it will be soon .

1、 Define variables and constants

var Defining variables ,let Define constants .

such as :

var test = 1
test = 2  // Variables can change values 

let test = 1
test = 2   // Constants cannot change values , The compiler will report an error 

var test1=1,test2=2,test3=3  // Separate multiple variables with commas 

2、 Add type labels

stay var test = 1 In this example .test By swift Judgment for int type .

swift It's type safe .

var test: Int = 1 This definition is the same as the above . Just for test This variable adds a type annotation . tell swfit No need to judge .

3、 Basics data type

Int Represents an integer value ;Double and Float Represents a floating-point value ;Bool Is a Boolean value ;String It is text data ;Character Is a character type .Swift There are also two main collection types .Array and Dictionary

4、 Global output function println and print

Everybody knows that , The difference between line breaking and no line breaking . Output to console .

such as :println(“this is my first swift test”)

Now let's put the above definition test How to output ?

println(“test value = \(test)”)

Swift Use string interpolation (string interpolation) Add the constant name or variable name to the long string as a placeholder ,Swift These placeholders will be replaced with the value of the current constant or variable , Namely \()

5、 gaze // When you gaze /* */ Fragment gaze

6、 A semicolon But if you want, don't . arbitrarily , But if you write multiple independent statements on one line, you need semicolons

such as :let test = “test”;println(test)

7、 Integers Integers are divided into signed ( just , negative ,0) And no sign ( just ,0)

Swift Provides 8,16.32 and 64 Signed and unsigned integer types of bits . These integer types and C The way languages are named is very similar . example 8 The bit unsigned integer type is UInt8.32 Bit signed integer type is Int32.

It's like Swift Like other types of . Integer types are named in uppercase .

let minValue = UInt8.min  // minValue  by  0. yes  UInt8  The minimum value of a type 
let maxValue = UInt8.max  // maxValue  by  255. yes  UInt8  Maximum of type 

Int and UInt

Generally speaking . You don't have to specify the length of an integer .Swift Provides a special integer type Int, The length is the same as the native word length of the current platform :

stay 32 A platform ,Int and Int32 Same length .

stay 64 A platform ,Int and Int64 Same length .

Swift It also provides a special unsigned type UInt, The length is the same as the native word length of the current platform :

stay 32 A platform .UInt and UInt32 Same length . stay 64 A platform ,UInt and UInt64 Same length

8、 Floating point numbers

Double and Float

Floating point numbers are numbers with decimal parts

Floating point types represent a larger range than integer types . Can store more than Int Numbers of larger or smaller types .

Swift Two types of signed floating point numbers are provided :

Double Express 64 Bit floating point . Use this type when you need to store very large or high-precision floating-point numbers .

Float Express 32 Bit floating point .

This type can be used if the accuracy requirement is not high .

Double Very high accuracy . There are at least 15 Digit number , and Float At least there is only 6 Digit number . Which type to choose depends on the range of values your code needs to handle .

9、 Numerical literal quantity

Whole numbers can be written :

A decimal number . Without a prefix A binary number . The prefix is 0b An octal number , The prefix is 0o A hexadecimal number . The prefix is 0x

Floating point literals can be decimal ( Without a prefix ) Or hexadecimal ( The prefix is 0x). There must be at least one decimal digit on either side of the decimal point ( Or hexadecimal numbers ). Floating point literal another optional exponent (exponent). In decimal floating-point numbers, through uppercase or lowercase e To specify the . In hexadecimal floating-point numbers, through uppercase or lowercase p To specify the .

Suppose the exponent of a decimal number is exp. So this number is the sum of the cardinal number and 10^exp The product of the :

1.25e2 Express 1.25 × 10^2, be equal to 125.0. 1.25e-2 Express 1.25 × 10^-2, be equal to 0.0125.

Suppose the exponent of a hexadecimal number is exp, So this number is the sum of the cardinal number and 2^exp The product of the :

0xFp2 Express 15 × 2^2, be equal to 60.0. 0xFp-2 Express 15 × 2^-2, be equal to 3.75. The following floating-point literals are all equal to decimal 12.1875:

let decimalDouble = 12.1875 let exponentDouble = 1.21875e1 let hexadecimalDouble = 0xC.3p0 Numeric literals can include additional formatting to enhance readability . Both integers and floating-point numbers can add extra zeros and include underscores , It doesn't affect the literal :

let paddedDouble = 000123.456 let oneMillion = 1_000_000 let justOverOneMillion = 1_000_000.000_000_1

It looks like a headache , Wouldn't it be better to use decimal system if it was so troublesome ... I make complaints about it It's still a little useful .

..

10、 Type conversion of character type

var one: Int = 10
var two = 3.11
var three = Double(one) + two  //Double There are integer constructors , Handle as other integer types , Here is a demonstration sample 

11、 Boolean value true false

12、 Type the alias typealias

Change the name of integer , It doesn't make much sense .

Poor reading .. such as

typealias MyInt = Int
var test: MyInt = 123

13、 Tuples This is very important

Tuples (tuples) Combine multiple values into a composite value .

Values in tuples can make arbitrary types . It is not required to be of the same type .

For example, create a (Int,String) Tuples of type : (500,”server error”)

let Mytuples = (500,"server error") // Define a tuple 
let (code,message) = Mytuples      // Decompose tuple data and output 
let (code,_) = Mytuples             // Just need the first value  . Unnecessary use _ Show me 
println("code is \(code)")         // Output 500
println("code is \(Mytuples.0)")   // Access by subscript    Output 500
let Mytuples2 = (code:500,message:"server error")   // Define a tuple with parameter name 
println("code is \(Mytuples2.code)");// Access by tuple element name    Output 500 

14、 optional type

Use optional types (optionals) To handle possible missing values .

Optional types indicate :

Valuable , be equal to x perhaps No value nil

let possibleNumber = “123” let convertedNumber = possibleNumber.toInt() // convertedNumber Guessed as type “Int?

“, Or type “optional Int” because toInt Methods can fail . So it returns an optional type (optional)Int, Instead of a Int. An optional one Int Be written Int?

instead of Int. The question mark implies that the included value is an optional type , That is to say, it may include Int Values may also not include values .

( It cannot include any other value, such as Bool Value or String value . It can only be Int Or nothing .)

if convertedNumber {
    println("\(possibleNumber) has an integer value of \(convertedNumber!)")
} else {
    println("\(possibleNumber) could not be converted to an integer")
}
//  Output  "123 has an integer value of 123"

You can add an exclamation point after the optional name (!) To get the value

How troublesome it is We have to infer whether the variable has a value : use if infer , Reuse ! Perform forced parsing .

Ability to simplify code with optional bindings :

if let actualNumber = possibleNumber.toInt() {
    println("\(possibleNumber) has an integer value of \(actualNumber)")
} else {
    println("\(possibleNumber) could not be converted to an integer")
}
//  Output  "123 has an integer value of 123"

It can also be handled by implicitly resolving optional types ( Make sure that variables always have values , Otherwise it will go wrong )

let assumedString: String! = "An implicitly unwrapped optional string."
println(assumedString)  //  There is no need to exclamation point 
//  Output  "An implicitly unwrapped optional string."

15、 Assertion Inferential logic true Continue operation false The end of the application

such as :let a = 1;assert(a >= 0) It will trigger

Copyright notice : This article is the original article of the blogger . Blog , Do not reprint without permission .

Publisher : Full stack programmer stack length , Reprint please indicate the source :https://javaforall.cn/116776.html Link to the original text :https://javaforall.cn

原网站

版权声明
本文为[Full stack programmer webmaster]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207061935439443.html