Ios swift learning diary 2-basic part, iosswift
The basic part of Swift is a new language for iOS and OS X application development. However, if you have C or Objective-C development experience, you will find that many Swift content is familiar to you.
The Swift type is proposed based on C and Objective-C. Int is an integer, Double and Float are floating-point, Bool is a Boolean, and String is a String. Swift also has two useful collection types: Array and Dictionary. See Collection types.
Just like the C language, Swift uses variables for storage and uses variable names to associate values. Variable with immutable values is widely used in Swift. They are constants and are more powerful than constants in C. In Swift, if the value you want to process does not need to be changed, using constants can make your code safer and better express your intent.
In addition to the familiar types, Swift also adds types that are not in Objective-C, such as Tuple ). Tuples allow you to create or pass a set of data. For example, when you return a value as a function, you can use a single tuple to return multiple values.
Swift also adds the Optional (Optional) Type to handle missing values. (Optional) "there is a value and it is equal to x" or "there is no value ". Optional is a bit like using nil in Objective-C, but it can be used on any type, not just a class. The optional type is more secure and expressive than the nil pointer in Objective-C, and is an important part of Swift's many powerful features.
Swift is a type-safe language. The optional language is a good example. Swift allows you to clearly understand the value type. If your code expects a String, type security will prevent you from accidentally passing in an Int. You can detect and correct errors as early as possible during the development phase.
Constants and variables
Constants and variables associate a name (such as maximumNumberOfLoginAttempts or welcomeMessage) with a specified type of value (such as number 10 or string "Hello. Once set, the constant value cannot be changed, and the variable value can be changed at will.
Declare constants and variables
Constants and variables must be declared before use. let is used to declare constants and var is used to declare variables. The following example shows how to use constants and variables to record the number of user attempts to log on:
Let maximumNumberOfLoginAttempts = 10
Var currentLoginAttempt = 0
The two lines of code can be understood:
"Declare a new constant named maximumNumberOfLoginAttempts and give it a value of 10. Then, declare a variable named currentLoginAttempt and initialize its value to 0 ."
In this example, the maximum number of allowed logon attempts is declared as a constant, because this value will not change. The number of logon attempts is declared as a variable, because this value must be added when logon attempts fail.
You can declare multiple constants or variables in a row, separated by commas:
Var x = 0.0, y = 0.0, z = 0.0
Note:
If your code has a value that does not need to be changed, use the let keyword to declare it as a constant. Declare the value to be changed as a variable.
Type Annotation
When declaring a constant or variable, you can add type annotation to indicate the type of the value to be stored in the constant or variable. If you want to add a type annotation, you need to add a colon and space after the constant or variable name, and then add the type name.
This example adds a type annotation to the welcomeMessage variable, indicating that the variable can store values of the String type:
Var welcomeMessage: String
The colon in the Declaration represents "Yes... type", so this line of code can be understood:
"Declare a variable of the String type and the name is welcomeMessage ."
"String type" means "any String type value can be stored ."
The welcomeMessage variable can now be set to any string:
WelcomeMessage = "Hello"
Note:
Generally, you rarely need to write type annotations. If you assign an initial value when declaring a constant or variable, Swift can infer the type of the constant or variable. For details, refer to type security and type inference. In the preceding example, the welcomeMessage is not assigned an initial value. Therefore, the type of the variable welcomeMessage is specified by a type annotation, rather than the initial value.
Constant and variable naming
You can use any character you like as the constant and variable name, including Unicode characters:
Let π = 3.14159
Let Hello = "Hello World"
Let ???? = "Dogcow"
Constants and variable names cannot contain mathematical symbols, arrows, reserved (or invalid) Unicode code bits, connections, and tabs. It cannot start with a number, but it can contain numbers elsewhere in the constant and variable name.
Once you declare a constant or variable as a definite type, you cannot declare it again with the same name or change the type of the stored value. At the same time, you cannot convert constants and variables.
Note:
If you need to use the same name as the reserved keyword of Swift as the constant or variable name, you can use reverse quotation marks (') to enclose the keyword as the name. In any case, you should avoid using keywords as constants or variable names unless you have no choice.
You can change the existing variable value to another value of the same type. In the following example, the value of friendlyWelcome ranges from "Hello! "Changed to" Bonjour! ":
Var friendlyWelcome = "Hello! "
FriendlyWelcome = "Bonjour! "
// FriendlyWelcome is now "Bonjour! "
Unlike variables, the constant value cannot be changed once determined. If you try this operation, an error will be reported during compilation:
Let your agename = "Swift"
LanguageName = "Swift ++"
// This will report the compile-time error-The languageName cannot be changed.
Output constants and variables
You can use the println function to output the value of the current constant or variable:
Println (friendlyWelcome)
// Output "Bonjour! "
Println is a global function used for output. The output content is wrapped in a line break. If you use Xcode, println will output the content to the console panel. (Another function is called print. The only difference is that the output content does not wrap .)
The input String value of the println function output:
Println ("This is a string ")
// Output "This is a string"
Similar to the NSLog function in Cocoa, the println function can output more complex information. This information can contain the values of the current constant and variable.
Swift uses string interpolation to add a constant or variable name to a long string as a placeholder. Swift replaces these placeholders with the values of the current constant or variable. Place the constant or variable name in parentheses and escape it with a backslash before the parentheses:
Println ("The current value of friendlyWelcome is \ (friendlyWelcome )")
// Output "The current value of friendlyWelcome is Bonjour!
Note:
For all available options for string interpolation, see string interpolation.
Note
Note the non-execution text in your code into prompts or notes for future reading. The Swift compiler automatically ignores the comments when compiling the code.
Notes in Swift are very similar to those in C. A single line comment starts with a double Forward slash:
// This is a comment
You can also perform multi-line comments, starting with a single forward slash followed by an asterisk (/*), ending with an asterisk and following a single forward slash (*/):
/* This is one,
Multi-line comment */
Unlike multi-line comments in C, Swift multi-line comments can be nested in other multi-line comments. You can create a multi-line comment block, and then nest it into a second multi-line comment block. When terminating a comment, insert the ending mark of the second comment block, and then insert the ending mark of the first comment block:
/* This is the beginning of the first multi-line comment
/* This is the second nested multi-line comment */
This is the end of the first multi-line comment */
By using nested multi-line comments, you can quickly and easily comment out a large piece of code, even if the Code already contains multi-line comments.
Semicolon
Unlike most other programming languages, Swift does not require you to use semicolons (;) at the end of each statement. Of course, you can add semicolons as you like. In one case, you must use a semicolon to write multiple independent statements in the same row:
Let cat = "?? "; Println (cat)
// Output "?? "
Integer
An integer is a number without decimal digits, such as 42 and-23. Integers can be signed (positive, negative, zero) or unsigned (positive, zero ).
Swift provides 8, 16, 32, and 64-Bit Signed and unsigned integer types. These integer types are similar to those in the C language. For example, the 8-bit unsigned integer type is UInt8, and the 32-bit signed integer type is Int32. Like other types of Swift, the integer type adopts the upper-case naming method.
Integer Range
You can access the min and max attributes of different integer types to obtain the maximum and minimum values of the corresponding types:
Let minValue = UInt8.min // The value of minValue is 0, which is the minimum value of the UInt8 type.
Let maxValue = UInt8.max // maxValue is 255, which is the maximum value of the UInt8 type.
Int
Generally, you do not need to specify the length of an integer. Swift provides a special integer Int with the same length as the native character of the current platform:
On a 32-bit platform, Int and Int32 are of the same length.
On a 64-bit platform, Int and Int64 are of the same length.
Unless you need an integer of a specific length, Int Is generally enough. This improves code consistency and reusability. Even on 32-bit platforms, Int can store an integer range of-2147483648 ~ 2147483647, most of the time this is big enough.
UInt
Swift also provides a special unsigned UInt with the same length as the native character of the current platform:
On a 32-bit platform, UInt and UInt32 are of the same length.
On a 64-bit platform, the length of UInt is the same as that of UInt64.
Note:
Do not use UInt unless you really need to store an unsigned integer with the same native character length as the current platform. In addition to this situation, it is best to use Int, even if the value you want to store is known to be non-negative. The unified use of Int can improve code reusability, avoid conversion between different types of numbers, and match the type speculation of numbers. Please refer to type security and type speculation.
Floating Point Number
A floating point number is a number with a decimal part, such as 3.14159, 0.1, and-273.15.
The floating point type has a larger range than the integer type. It can store numbers that are larger or smaller than the Int type. Swift provides two types of signed floating point numbers:
Double indicates a 64-bit floating point number. Use this type when you need to store large or high-precision floating point numbers.
Float indicates a 32-bit floating point number. This type can be used if the precision requirement is not high.
Note:
Double has a high precision, with at least 15 digits while Float has at least 6 digits. The type you select depends on the range of values to be processed by your code.
Type security and speculation
Swift is a type safe language. The Type-safe language allows you to clearly understand the type of the value to be processed by the Code. If your code requires a String, you cannot accidentally upload it to an Int.
Because Swift is type-safe, it performs type check (type checks) when compiling your code and marks mismatched types as errors. This allows you to detect and fix errors as soon as possible during development.
When you want to process different types of values, the type check can help you avoid errors. However, this does not mean that you need to explicitly specify the type every time you declare constants and variables. If you do not explicitly specify a type, Swift uses type inference to select the appropriate type. With the speculative type, the compiler can automatically deduce the type of the expression when compiling the code. The principle is very simple. You only need to check the value you assigned.
Because of the speculative type, Swift seldom needs to declare the type compared with C or Objective-C. Although constants and variables need to be clearly typed, most of the work does not need to be done by yourself.
Type estimation is useful when you declare constants or variables and assign the initial values. When you declare constants or variables, assign them a literal value (literal value or literal) to trigger type speculation. (Literally, it is the value that appears directly in your code, such as 42 and 3.14159 .)
For example, if you assign a new constant value of 42 without specifying the type, Swift can deduce that the constant type is Int, because the initial value you assign to it looks like an integer:
Let meaningOfLife = 42
// MeaningOfLife is assumed to be of the Int type.
Similarly, if you do not specify the type for the floating point literal, Swift will assume that you want Double:
Lets pi = 3.14159
// Pi is assumed to be of the Double type.
When we speculate on the floating point type, Swift always chooses Double instead of Float.
If the expression contains both integers and floating-point numbers, it is assumed to be of the Double type:
Let anotherPi = 3 + 0.14159
// AnotherPi is assumed to be of the Double type.
The original value 3 does not explicitly declare the type, but the expression contains a floating point literal, so the expression is assumed to be of the Double type.
Numeric literal
An integer literal can be written as follows:
One decimal number with no prefix
A binary number with a prefix of 0 B
An octal number with a prefix of 0 o
A hexadecimal number with a prefix of 0x
The decimal values of all the following integers are 17:
Let decimalInteger = 17
Let binaryInteger = 0b10001 // 17 of Binary
Let octalInteger = 0o21 // 17 of the 8 th Node
Let hexadecimalInteger = 0x11 // hexadecimal 17
The floating point literal can be in decimal format (without a prefix) or hexadecimal format (with a prefix of 0x ). There must be at least one decimal number (or a hexadecimal number) on both sides of the decimal point ). The floating point literal also has an optional index (exponent), which is specified in the decimal floating point number through the upper or lower case e. It is specified in the hexadecimal floating point number through the upper or lower case p.
If the exponent of a decimal number is exp, the number is equivalent to the product of base number and 10exp:
1.25e2 indicates 1.25x102, or 125.0.
1.25e-2 indicates 1.25 × 10? 2, equal to 0.0125.
If the exponent of a hexadecimal number is exp, the number is equivalent to the product of base and 2exp:
0xFp2 indicates 15 × 22, equal to 60.0.
0xFp-2 indicates 15 × 2? 2, equal to 3.75.
The following floating point literal is equal to 12.1875 in decimal format:
Let decimalDouble = 12.1875
Let exponentDouble = 1.21875e1
Let hexadecimalDouble = 0xC. 3p0
The numeric literal can include additional formats to enhance readability. Both integers and floating-point numbers can be added with extra zeros and underscores, without affecting the literal volume:
Let paddedDouble = 000123.456
Let oneMillion = 0000000_000
Let justOverOneMillion = 0000000_000.000_000_1
Numeric type conversion
Generally, even if the Integer constants and variables in the Code are known to be non-negative, use the Int type. Always use the default Integer type to ensure that your Integer constants and variables can be reused directly and can match the type estimation of the integer literal. Other integer types are used only when necessary, for example, to process data with clear external lengths or to optimize performance and memory usage. When explicitly specified data types are used, value overflow can be detected in a timely manner and special data is being processed.
Integer Conversion
Variables and constants of different integer types can store numbers of different ranges. Int8 constants or variables can store numbers ranging from-128 ~ 127, while the number range of UInt8 constants or variables that can be stored is 0 ~ 255. If the number is out of the storage range of constants or variables, an error is reported during compilation:
Let cannotBeNegative: UInt8 =-1
// The UInt8 type cannot store negative numbers, so an error is reported.
Let tooBig: Int8 = Int8.max + 1
// The Int8 type cannot store more than the maximum value, so an error is returned.
Since each integer type can store values of different ranges, You must select numeric type conversion based on different situations. This selective method can prevent implicit conversion errors and clarify the type conversion intent in your code.
To convert one numeric type to another, you must use the current value to initialize a new expected numeric type, which is your target type. In the following example, the constant twoThousand is of the UInt16 type, but the constant one is of the Uint8 type. They cannot be directly added because they have different types. Therefore, you must call UInt16 (one) to create a new UInt16 number and use the value of one for initialization. Then, use this new number for calculation:
Let twoThousand: UInt16 = 2_000
Let one: UInt8 = 1
Let twoThousandAndOne = twoThousand + UInt16 (one)
Now the two numbers are of the UInt16 type and can be added. The type of the target constant twothousandone is assumed to be UInt16 because it is the sum of two UInt16 values.
SomeType (ofInitialValue) is the default method for calling the Swift constructor and passing in an initial value. Within the language, UInt16 has a constructor that accepts a UInt8 value. Therefore, this constructor can use the existing UInt8 to create a new UInt16. Note: you cannot input any type of value. You can only input the value of the constructor within UInt16. However, you can extend the existing type so that it can receive values of other types (including custom types). For more information, see extend.
Integer and floating point conversion
The type must be explicitly specified for integer and floating-point conversions:
Let three = 3
Let pointOneFourOneFiveNine = 0.14159
Let pi = Double (three) + pointOneFourOneFiveNine
// Pi equals 3.14159, so it is assumed to be of the Double type.
In this example, the value of the constant three is used to create a value of the Double type, so the number types on both sides of the plus sign are the same. If no conversion is performed, the two cannot be added.
The reverse conversion from a floating point to an integer is the same. The integer type can be initialized using the Double or Float type:
Let integerPi = Int (pi)
// IntegerPi is equal to 3, so it is assumed to be of the Int type.
When a new integer is initialized in this way, the floating point value is truncated. That is to say, 4.75 is changed to 4, and-3.9 is changed to-3.
Note:
The combination of numeric constants and variables is different from the combination of numeric literal. Literal 3 can be directly added to a word surface by 0.14159, because the numeric literal itself does not have a clear type. Their types are inferred only when the compiler requires a value.
Type alias
A type aliases is another name defined for an existing type. You can use the typealias keyword to define the type alias.
A type alias is useful when you want to give a more meaningful name to an existing type. Assume that you are processing data of external resources of a specific length:
Typealias AudioSample = UInt16
After defining a type alias, you can use the alias wherever the original name is used:
Var maxAmplitudeFound = AudioSample. min
// MaxAmplitudeFound is now 0
In this example, AudioSample is defined as an alias of UInt16. Because it is an alias, AudioSample. min is actually UInt16.min, so an initial value 0 is assigned to maxAmplitudeFound.
Boolean Value
Swift has a basic Boolean Type called Bool. Boolean values are logical values because they can only be true or false. Swift has two Boolean constants: true and false:
Let orangesAreOrange = true
Let turnipsAreDelicious = false
The orangesAreOrange and turnisaredelicious types are inferred to be Bool, because their initial values are Boolean literal values. Like Int and Double, If you assign true or false values to variables when creating them, you do not need to declare constants or variables as the Bool type. When initializing a constant or variable, if the assigned value type is known, type speculation can be triggered, which makes Swift code more concise and readable.
When you write conditional statements such as if statements, Boolean values are very useful:
If turnipsAreDelicious {
Println ("Mmm, tasty turnips! ")
} Else {
Println ("Eww, turnips are horrible .")
}
// Output "Eww, turnips are horrible ."
Conditional statements, such as if, refer to control flow.
If you use a non-Boolean value where the Bool type is required, the Swift type Security Mechanism reports an error. The following example reports a compilation error:
Let I = 1
If I {
// This example will not pass compilation and an error will be reported
}
However, the following example is valid:
Let I = 1
If I = 1 {
// This example will be compiled successfully.
}
The comparison result of I = 1 is of the Bool type, so the second example can pass the type check. For comparison similar to I = 1, see Basic operators.
Like other types of security examples in Swift, this method can avoid errors and ensure that the intent of this Code is always clear.
Tuples
Tuples combines multiple values into a compound value. The value in the meta-group can be of any type, but it is not required to be of the same type.
In the following example, (404, "Not Found") is a tuple describing the HTTP status code. The HTTP status code is a special value returned by the web server when you request a webpage. If the requested webpage does Not exist, a 404 Not Found status code is returned.
Let http404Error = (404, "Not Found ")
// The type of http404Error is (Int, String), and the value is (404, "Not Found ")
(404, "Not Found") tuples combine an Int value and a String value to indicate two parts of the HTTP status code: a number and a human-readable description. This tuples can be described as "a type of (Int, String) tuples ".
You can combine any sequence of types into a single tuple, which can contain all types. As long as you want, you can create a type of (Int, Int, Int), (String, Bool), or any other tuples that you want to combine.
You can break down the content of a tuples (decompose) into separate constants and variables, and then you can use them normally:
Let (statusCode, statusMessage) = http404Error
Println ("The status code is \ (statusCode )")
// Output "The status code is 404"
Println ("The status message is \ (statusMessage )")
// Output "The status message is Not Found"
If you only need a part of the values of the tuples, you can mark the ignored parts with underscores:
Let (justTheStatusCode, _) = http404Error
Println ("The status code is \ (justTheStatusCode )")
// Output "The status code is 404"
In addition, you can use subscript to access a single element in the tuples. The subscript starts from scratch:
Println ("The status code is \ (http404Error. 0 )")
// Output "The status code is 404"
Println ("The status message is \ (http404Error. 1 )")
// Output "The status message is Not Found"
You can name a single element when defining the tuples:
Let http200Status = (statusCode: 200, description: "OK ")
After naming the elements in the tuples, you can obtain the values of these elements by name:
Println ("The status code is \ (http200Status. statusCode )")
// Output "The status code is 200"
Println ("The status message is \ (http200Status. description )")
// Output "The status message is OK"
Tuples are useful when they are returned as function values. A function used to obtain a webpage may return a (Int, String) tuples to describe whether the webpage is obtained successfully. Compared with returning only one type of value, a tuples containing two different types of values can make the function return more useful information. For details, refer to "parameter values" and "Return Value" (06_functions.html # Function_Parameters_and_Return_Values ).
Note:
Tuples are useful for temporary organization values, but they are not suitable for creating complex data structures. If your data structure is not used temporarily, use a class or struct instead of a tuples. See classes and struct.
Optional
Use optional (optionals) to handle possible missing values. Optional values:
Value, equal to x
Or
No value
Note:
C and Objective-C do not have the optional concept. The closest thing is a feature in Objective-C. If a method does not return an object or nil, nil indicates "a valid object is missing ". However, this only works for objects-for struct, the basic C type or enumeration type does not work. For these types, the Objective-C method generally returns a special value (such as NSNotFound) to indicate that the value is missing. This method assumes that the caller of the method knows and remembers to judge the special value. However, the Swift option allows you to imply that any type of value is missing without a special value.
Let's look at an example. The Swift String type has a method called toInt, which is used to convert a String value into an Int value. However, not all strings can be converted into an integer. The string "123" can be converted to a number 123, but the string "hello, world" cannot.
The following example uses the toInt method to convert a String to an Int:
Let possibleNumber = "123"
Let convertedNumber = possibleNumber. toInt ()
// ConvertedNumber is assumed to be of the type "Int? ", Or type" optional Int"
Because the toInt method may fail, it returns an optional (optional) Int instead of an Int. An optional Int is written as an Int? Instead of Int. The question mark implies that the included value is optional, that is, it may contain an Int value or not. (It cannot contain any other value, such as a Bool value or a String value. It can only be Int or nothing .)
If statement and forced resolution
You can use the if statement to determine whether an optional value is included. If the value is optional, the result is true. If there is no value, the result is false.
After you confirm that the optional package does contain values, you can add an exclamation point (!) after the optional name (!) To obtain the value. This exclamation point indicates "I know this option has a value. Please use it ." This is called mandatory resolution of optional values (forced unwrapping ):
If convertedNumber {
Println ("\ (possibleNumber) has an integer value of \ (convertedNumber !) ")
} Else {
Println ("\ (possibleNumber) cocould not be converted to an integer ")
}
// Output "123 has an integer value of 123"