IOS development language Swift getting started-Basics

Source: Internet
Author: User

IOS development language Swift getting started-Basics

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 content> Swift> is familiar to you.
The Swift> type is proposed based on> C> and> Objective-C>. Int is an integer type, Double and Float are floating point types, Bool is a boolean type, and String is a String. Swift also has two useful collection types: Array and Dictionary. See Collection types.
Just like> C> language,> Swift> uses variables for storage and variable names for value Association. In> Swift>, variable with variable values is widely used. They are constants and are more powerful than constants in C language. In> Swift>, if the value you want to process does not need to be changed, you can use constants to make your code safer and better express your intent.
In addition to the familiar types, Swift> also adds types that are not included 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> the Optional (Optional) Type is added to process missing values. (Optional) "there is a value, and it is equal to> x>" or "there is no value ". Optional, it 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>. It is an important part of> Swift> many powerful features.
Swift> is a type-safe language. The optional language is a good example. Swift> let you know the type of the value clearly. 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 = 10var 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 statement indicates "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

Let π = 3.14159let Hello = "Hello World" let = "dogcow" variable name contains numbers elsewhere.

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 is changed 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" Your agename = "Swift ++" // This will report the compile-time error-Your agename cannot be changed
Output constants and variables

You can use println

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, 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

Notes in Swift are very similar to those in C. Single line comment with 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 a multi-line comment */

Nested into the second multi-line comment. 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, the 32-bit has a character, and the 32-bit signed integer type is Int32. Just 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 UInt8 type. let maxValue = UInt8.max // The value of maxValue is 255, which is the maximum value of 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 inference of numbers. For details, see type security and type inference.

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 type inference

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 the mismatched type as an error. 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 type inference, 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 there is a type inference, compared with> C> or> Objective-C>,> Swift> rarely needs to declare the type. Although constants and variables need to be clearly typed, most of the work does not need to be done by yourself.

Type inference is useful when you declare a constant or variable and assign an initial value. When you declare constants or variables, assign them a literal (literal value or literal) to trigger type inference. (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 infer 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 infer that you want a Double:

Let pi = 3.14159 // pi is assumed to be of the Double type.

When the floating point type is inferred, Swift> always chooses Double instead of Float.

If the expression contains both integers and floating-point numbers, it is inferred 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 inferred 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 = 17let binaryInteger = 0b10001 // binary 17let octalInteger = 0o21 // 17let 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 10 ^ exp:

1.25e2 indicates 1.25x10 ^ 2, or 125.0.
1.25e-2 indicates 1.25x10 ^-2, which is equal to 0.0125.
If the exponent of a hexadecimal number is exp, the number is equivalent to the product of the base number and 2 ^ exp:

0xFp2 indicates 15 × 2 ^ 2, 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.1875let exponentDouble = 1.21875e1let 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.456let oneMillion = 1_000_000let justOverOneMillion = 1_000_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 inference 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. Therefore, the error "let tooBig: Int8 = Int8.max + 1 // The Int8 type cannot store more than the maximum value, so an error is reported.

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_000let one: UInt8 = 1let 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 inferred 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 = 3let pointOneFourOneFiveNine = 0.14159let pi = Double (three) + pointOneFourOneFiveNine // pi is equal to 3.14159, so it is assumed that 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 must be 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 = truelet turnipsAreDelicious = false

The orangesAreOrange and turnisaredelicious types are inferred to be Bool, because their initial values are Boolean. 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 constants or variables, if the assigned value type is known, type inference 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 = 1if I {// This example will not pass compilation and an error will be reported}

However, the following example is valid:

Let I = 1if 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) = http404Errorprintln ("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, _) = http404Errorprintln ("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. See 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
Optional type (optionals) is used to handle possible missing values. Optional type:

Value, equal to x
Or

No value
Note:
C and Objective-C do not have the optional type 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 optional type of Swift 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 the number 123, but the string "hello, world" does not work.

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 type (optional) Int instead of an Int. An optional Int is written as an Int? Instead of Int. The question mark implies that the included values are optional, that is, they may contain Int values 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 optional type has a value, the result is true; if there is no value, the result is false.

After you confirm that the optional type does contain a value, 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"

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.