Swift Learning Notes-Tutorial learning a basic article

Source: Internet
Author: User
Tags aliases

1.1 Constants and variables (Constants and Variables)

Constants and variables associate a name with a value of a specified type. Constants (values that do not need to be changed) value cannot be changed once set, and the value of the variable can be changed arbitrarily. If possible, use constants as much as possible.

Declaration declaring Constants and Variables

Constants and variables must be declared before use, declare constants with Let, and declare variables with VAR.

Let maximumnumberofloginattempts = 10

var currentloginattempt = 0

You can declare multiple constants or multiple variables in a single line, separated by commas:

var x = 0.0, y =0.0, z = 0.0

Type callout Types Annotations

Describes the type of the value to be stored in a constant or variable.

var welcomemessage:string//Variable welcomemessage is a string type

var red, Green, blue:double

Named naming Constants and Variables

Cannot contain white space characters (whitespace, tab, and enter), mathematical symbols, arrows, private and illegal Unicode codes, encapsulated characters (Line-and box-drawing characters). You cannot start with a number, and you cannot define the same name repeatedly.

letπ= 3.14159

Let's Hello = "Hello World"

Let???? = "Dogcow"//Head of dog and cow

var friendlywelcome = "Hello!"

Friendlywelcome = "bonjour!"

1.2 statements, semicolons, and annotations (Comment)

The general line is a statement with no semicolon at the end.

Single-line Comment

/* */Multi-line comments, can be nested. By using nested multiline annotations, you can quickly and easily comment out a large piece of code, even though the code already contains a multiline comment block

/*a complete, Swift command is A statement. The typical layout of a program is one statement, one line:*/

Print ("Hello,")

Print ("world!")

Print ("Hello,"); Print ("world!")

1.3 Type-safe and type-inferred type Safety and types inference

type safety: helps you to clearly know the type of value the code is dealing with, and if the code wants a string, when you accidentally use or pass in an int, or other type, the compile-time type security check will alert you. Constants, variables, and functions all have types.

integer integers : Swift provides 8,16,32 and 64-bit signed and unsigned integer types.

Int

On 32-bit platforms, Int and Int32 are the same length.

On 64-bit platforms, Int and Int64 are the same length.

UInt

On 32-bit platforms, the UINT and UInt32 are the same length.

On 64-bit platforms, UInt and UInt64 are the same length

Floating point floating-point Numbers

A Double represents a 64-bit floating-point number. Use this type when you need to store large or very high-precision floating-point numbers.

Float represents a 32-bit floating-point number. This type can be used if the accuracy requirement is not high.

type inference: If you do not explicitly specify a type, Swift uses type inference (inference) to select the appropriate type. With type inference, the compiler can automatically infer the type of an expression when compiling code. The principle is simple, just check your assigned value.

Type inference is useful when you declare constants or variables and assign initial values. You can trigger type inference when you declare constants or variables by assigning them a literal (literal value or literal).

Let Meaningoflife =42

Meaningoflife will be assumed to be of type Int

Let pi = 3.14159

Pi is assumed to be Double type

When you infer the type of a floating-point number, Swift always chooses Double instead of float.

If both integers and floating-point numbers appear in the expression, they are inferred as Double types:

Let Anotherpi = 3 +0.14159

Anotherpi is presumed to be a Double type.

1.4 Numeric literal numeric literals

The literal is the value that will appear directly in your code (aliteral value is a value that appears directly in your source code).

Let Decimalinteger =17

Let Binaryinteger =0b10001//binary 17, beginning with 0b

Let Octalinteger =0o21//Eight binary 17, beginning with 0o

Let Hexadecimalinteger = 0x11//16 binary 17, beginning with 0x

The exponent is the exp decimal, which is the radix multiplied by 10exp:

1.25e2 means 1.25 x102, or 125.0.

1.25e-2 means 1.25 x10-2, or 0.0125.

The exponent is exp hexadecimal, which is the radix multiplied by 2exp:

0XFP2 means x, or 60.0.

0xfp-2 means x2-2, or 3.75.

Let Paddeddouble =000123.456

Let Onemillion =1_000_000

Let justoveronemillion = 1_000_000.000_000_1

1.5 Numeric type conversion numeric type Conversion

integers use the int type as much as possible to ensure that your integer constants and variables can be reused directly and can match the type inference of the integer class literal.

Integer conversion int Conversion

Variables and constants of different integer types can store numbers of different ranges.

The Int8 number range is -128 to 127, and the UInt8 number range is 0 to 255.

Let twothousand:uint16 = 2_000

Let One:uint8 = 1

Let Twothousandandone = Twothousand + UInt16 (one)

Now the two number types are UInt16 and can be added. The type of the target constant twothousandandone is inferred as UInt16 because it is the and of two UInt16 values.

Integer and floating-point number conversion integer and floating-point Conversion

The conversion of integers and floating-point numbers must explicitly specify the type:

Let three = 3

Let Pointonefouronefivenine = 0.14159

Let Pi =double (three) + Pointonefouronefivenine

Pi equals 3.14159, so it is assumed to be Double type

In this example, the constant three value is used to create a value of type Double, so the number on both sides of the plus sign must be the same. If you do not convert, both cannot be added.

The inverse conversion of floating-point numbers to integers is the same line, and integer types can be initialized with double or Float types:

Let Integerpi =int (PI)

Integerpi equals 3, so it is assumed to be of type Int

When a new integer value is initialized in this way, the floating-point value is truncated. That means 4.75 will become 4, 3.9 will become-3.

1.6 Types Alias Type Aliases

Type aliases are useful when you want to give a more meaningful name to an existing type. Suppose you are working with data for a specific length of external resource:

Typealias audiosample = UInt16

var maxamplitudefound = Audiosample.min

Maxamplitudefound is now 0.

1.7 Boolean value Booleans

Boolean values can only be true or false. Swift has a basic Boolean type bool, with two Boolean constants, True and false:

Let Orangesareorange = True

Let turnipsaredelicious = False

1.8-Tuple tuples

Tuples combines multiple values into a single composite value. The values within the tuple can be any type and do not require the same type.

Let Http404error = (404, "not Found")

The type of Http404error is (Int, String), the value is (404, "not Found")

You can break down the contents of a tuple into separate constants and variables:

Let (StatusCode, statusmessage) = Http404error

Print ("The Status code is \ (StatusCode)")

Output "The Status code is404"

If you only need a subset of the tuple values, you can mark the part you want to ignore with an underscore (_) when decomposing:

Let (Justthestatuscode, _) = Http404error

Print ("The Status code is \ (Justthestatuscode)")

Output "The Status code is404"

In addition, you can use the subscript to access a single element in a tuple, with the subscript starting from zero:

Print ("The Status code is \ (http404error.0)")

Output "The Status code is404"

Print ("The status message is \ (Http404error.1)")

Output "The status message is NotFound"

You can name a single element when you define a tuple: You can get the values of these elements by name:

Let Http200status = (statuscode:200, description: "OK")

Print ("The Status code is \ (Http200status.statuscode)")

Output "The Status code is200"

Print ("The status message is \ (http200status.description)")

Output "The status message IsOK"

1.9 Optional Type Optionals

An optional type means: There is a value equal to X or no value. Expressed as: type?

Let Possiblenumber = "123"

Let Convertednumber = Int (possiblenumber)

Convertednumberis inferred to be of type "int?", or "optional int"

Because the constructor might fail, it returns an optional type int instead of an int.

Nil

You can assign a value of nil to an optional variable to indicate that it has no value:

var serverresponsecode:int? = 404

Serverresponsecode contains an actual Int value of 404

Serverresponsecode = Nil

Serverresponsecode now contains no value

When you define an optional variable, the variable automatically takes the value nil if it is not assigned at the same time.

var surveyanswer:string?

Surveyanswer is automatically set to nil

If statement and forced parsing if statements and forced unwrapping

You can use the IF statement and the nil comparison (equals (= =) or unequal (! =) to determine whether an optional value contains a value.

When you are sure that the optional type does contain a value, you can get the value by adding an exclamation point (!) after the optional name. This exclamation point says "I know this option has a value, please use it." "This is called forced parsing of optional values:

If Convertednumber! = Nil {

Print ("Convertednumber have an integer value of\ (convertednumber!).")

}

Prints "Convertednumber have an integer value of 123."

Optional binding optional binding

Use an optional binding to determine whether an optional type contains a value, and assign the value to a temporary constant or variable if it contains a value. Using the IF or while

· If let constantname = someoptional{

· Statements

· }

If let Actualnumber =int (possiblenumber) {

Print ("\ \ \ (possiblenumber) \ ' Have an integer value of \ (Actualnumber)")

} else {

Print ("\ ' \ (possiblenumber) \ ' could not is converted to Aninteger")

}

Output "' 123 ' have an integer valueof 123"

The Actualnumber is only used to output conversion results.

You can include multiple optional bindings in the IF statement, and use the WHERE clause to make a Boolean judgment.

If Let firstnumber = Int ("4"), Secondnumber = Int ("") where Firstnumber < Secondnumber {

Print ("\ (Firstnumber) < \ (Secondnumber)")

}

Prints "4 < 42"

implicitly resolves an optional type implicitly unwrapped optionals

Sometimes in the program architecture, after the first assignment, you can determine that an optional type always has a value. An optional state of this type is defined as an implicitly resolved optional type (!). Basic types are followed by! Instead of?.

Let possiblestring:string? = "an optionalstring."

Let forcedstring:string = possiblestring! Requires an exclamation mark

Let assumedstring:string! = "an implicitlyunwrapped Optional string."

Let implicitstring:string = assumedstring//No need for an exclamation mark

If assumedstring! = Nil {

Print (assumedstring)

}

Prints "an implicitly unwrapped optionalstring."

If let definitestring = assumedstring {

Print (definitestring)

}

Prints "an implicitly unwrapped optionalstring."

Note: If a variable may later become nil , do not use implicit parsing of optional types. Use a normal optional type if you need to determine whether it is nil in the lifetime of the variable .

1.10 Base operator (basic Operators)

The swift operator has unary, two, and ternary operators.

1.10.1 assignment operator Assignment Operator =

Let B = 10//assigns the 10 to the left of the equal sign to the constant b

var a = 5

A = b//A is now 10

Let (x, y) = (1, 2)//x are equal to 1, and y are equal to 2

1.10.2 arithmetic operator arithmetic Operators
    • Addition (+) subtraction (-) multiplication (*) Division (/)

The addition operator can also be used for concatenation of strings:

"Hello," + "world"//equals "Hello, World"

The remainder operator remainder Operator

The remainder operation (a% B) calculates how many times B is just good enough to accommodate a, returning the extra portion

Floating-point calculation floating-point remainder calculations

8% 2.5//equals 0.5

unary minus operator unary minus Operator

Let three = 3

Let Minusthree =-three//-3

Let Plusthree =-minusthree

Unary positive operator unary Plus Operator

Let Minussix =-6

Let Alsominussix = +minussix

1.10.3 combination assignment operator (Compound assignment Operators)

var a = 1

A + = 2//A is now equal to 3

1.10.4 comparison operator Comparison Operators

• Equals (A = = b)

• Not equal to (a! = b)

• Greater than (a > B)

• Less than (a < b)

• Greater than or equal to (a >= b)

• Less than or equal to (a <= b)

1.10.53 Mesh operator Ternary Conditional Operator

If question {

Answer1

} else {

Answer2

}

Let Contentheight = 40

Let Hasheader = True

Let RowHeight = Contentheight + (hasheader? 50:20)

RowHeight is equal to 90

1.10.6 empty operator Nil coalescing Operator

The empty-fit operator (a?? b) makes an empty judgment on an optional type A, and if a contains a value, it is unpacked, otherwise a default value of B is returned. This operator has two conditions:

• Expression A must be of type optional

• The type of the default value B must be consistent with the type of a stored value

1.10.7 interval operator range operators closed interval operator closed range Operator

The Closed interval operator (A...B) defines an interval that contains all values from A to B (including A and b), and b must be greater than or equal to a.

Half open interval operator Half-open range Operator

Half open interval (a..) <B) defines a range from a to B, but not including B. The semi-open interval is called because the interval contains the first value and does not include the last value.

1.10.8 logical operator logical operators logical non logical NOT Operator

The logical non-operation (!a) deserializes a Boolean value so that true becomes false,false true.

Logic and Logical AND Operator

Logic with (a && b) expresses that the value of the entire expression is true when only the values of A and B are true. As long as any one value is false, the value of the entire expression is false.

Logical OR Logical OR Operator

Logic or (A | | b) indicates that one of the two logical expressions is true, and the entire expression is true.

Combination of logical operators computes combining Logical Operators

Swift logic operators && and | | is left-associative,&& and | | Only two values can be manipulated at all times.

Use parentheses to clarify priority explicit parentheses

Swift Learning Notes-Tutorial learning a basic 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.