Learn Swift notes starting from 0 (i)

Source: Internet
Author: User
Tags bitwise operators function definition

Swift is a new programming language for IOS and OS X apps, built on the best C and Objective-c languages, without the C language compatibility restrictions. Swift uses a secure programming model that adds modern functionality to make programming easier, more flexible, and more fun. Swift is supported by a mature and pampered Cocoa and Cocoa Touch Framework, an opportunity to reimagine software development.

-- my first line of Swift code

Import Foundation//indicates introduction of foundation framework

var str = "Hello World"//Declare str variable, var means declare variable

Print (str)//print (_:) is a function that can output variables or constants to the console

-- writing Swift code using a Web site

The SWIFT program cannot be compiled and run on other Windows platforms, and someone has provided a website swiftstub.com that can compile and run swift programs under any platform.

--swift 2.0 after the added keyword

After Swift 2.0, add the defer, guard, repeat, catch, rethrows, throw, throws, and try keywords, where the repeat keyword replaces do in the Do-while loop, that is, medium repeat- While loop. The Do keyword is used for error handling.     Catch, rethrows, throw, throws, and try are error-handling keywords. Error handling is the addition of new content after Swift 2.0.

-- writing Swift with the playground tool

The purpose of writing Swift code with playground is to learn, test algorithms, validate ideas, and visualize the results of the operation, not to make the final program compile and publish.
Playground program run ① area is code writing view, ② area is run result view, ③ area is timeline view, ④ area is console view, using log functions such as print to output the result to the console, you can hide and display the console by the button in the lower left corner.

--swift Identifiers and Keywords

Identifiers are names specified by the developer for variables, constants, methods, functions, enumerations, structs, classes, protocols, and so on.

Naming rules in Swift:

• Case-sensitive, myname and myname are two different identifiers;

• The first character of the identifier can begin with an underscore (_) or a letter, but not a number;

• Other characters in the identifier can be underscores (_), letters, or numbers.

There are 4 common keywords for swift language:

• Keywords related to declarations: class, Deinit, enum, and so on.

• Keywords related to statements: Break, case, continue, and so on.

• Expressions and Type keywords: as, catch, DynamicType, false, and so on.

• Keywords used in specific contexts: associativity, convenience, dynamic, and so on.

Note: The keywords in swift are case-sensitive, so class and class are different, so class is not a keyword for swift.

-- Constants and Variables

In Swift, declare a constant with Let, and declare a variable with var

I think: In principle, let is preferred, it has many advantages, it can prevent unnecessary changes in the process of running the program, improve the readability of the program. In particular, a let declaration is often used when referencing a data type declaration, although it is not a constant at the business level, but rather prevents the program from being incorrectly modified by its reference while it is running.

--swift 2.0 4 overloaded forms of the print function in

Print (_:). Output a variable or constant to the console, and wrap the line.

Print (_:_:). Outputs a variable or constant into a stream of the specified type, and wraps the line.

Print (_:appendnewline:). Output variable or constant to the console, the Appendnewline parameter is a Boolean value, True indicates a newline, and false means no line break.

Print (_:_:appendnewline:). An output variable or constant in a stream of a specified type, the Appendnewline parameter is a Boolean value, True indicates a newline, and false means no line break.

-- in Swift, there are 3 forms of an expression

1. Do not specify data type VARA1 = 10

2. Specify data type Vara1:int = 10

3, use semicolon Vara1:int = 10; var a2:int = 20

In the swift language, a semicolon can be added without a semicolon at the end of a statement, but there is a case where a semicolon is required, that is, when multiple statements are written in one line, a semicolon is used to differentiate the statement.
For example: var a1:int = 10; var a2:int = 20;

--swift the operator

The main operators in the swift language include arithmetic, relationships, logic, bitwise operators, and so on

Unary operators:
-Take inverse symbol negation operation
+ + Add a first value plus one, or add a value first
--Subtract one first, subtract one, or subtract the value again and again

Binary operators:
+ add sum, string join operation available with string type
-Reduce the difference in demand
* Multiply to find the product
/In addition to seeking business
The remainder is obtained by the residual

Several special operators:

? Reference number (.): an instance invokes an operator such as a property, method, and so on.

? Question mark (?): Used to declare an optional type.

? Exclamation point (!): A forced unpacking of an optional type value.

? Arrow (): Describes the function or method return value type.

? Colon operator (:): Used for dictionary collections to split "key value" pairs.

--swift data type in

Integer, float, Boolean, character, string these types are certain, where collections, enumerations, structs, and classes are also data types in Swift. Tuples are unique in swift.
Tuple is a kind of data structure, which is widely used in mathematics. In computer science, tuples are a basic concept in a relational database, one record in a tuple table, and each column is a field. So in the two-dimensional table, tuples are also called records.

Now using swift syntax to represent the student tuple is:

The first form of a notation

("1001", "Zhang San", 30, 90)

The second type of notation

(ID: "1001", Name: "Zhang San", English_score:30, chinese_score:90)

-- integer and floating-point types of data type

Swift provides signed and unsigned integers in 8, 16, 32, 64-bit form. These integer types follow the naming conventions of the C language, and I summarize the integral types in swift:

Example of an integral type:
Print ("UInt8 range: \ (uint8.min) ~ \ (Uint8.max)")
Print ("Int8 range: \ (int8.min) ~ \ (Int8.max)")
Print ("UInt range: \ (uint.min) ~ \ (Uint.max)")
Print ("UInt64 range: \ (uint64.min) ~ \ (Uint64.max)")
Print ("Int64 range: \ (int64.min) ~ \ (Int64.max)")
Print ("Int range: \ (int.min) ~ \ (Int.max)")
The output results are as follows:
UInt8 range:0 ~ 255
Int8 Range: 128 ~ 127
UInt range:0 ~ 18446744073709551615
UInt64 range:0 ~ 18446744073709551615
Int64 Range: 9223372036854775808 ~ 9223372036854775807
Int Range:-9223372036854775808 ~ 9223372036854775807

The preceding code calculates the range of each type through the Min and Max properties of integers.
Floating-point types are primarily used to store decimal values, and can be used to store large integers. It is divided into floating-point (float) and double-precision floating-point (double), double-precision floating-point numbers use more memory space than floating-point number, can represent the range of values and precision is also relatively large.

-- insertion, deletion, and substitution of strings

Splice (_:atindex:). Inserts a string at the index position.

Insert (_:atindex:). Inserts a character at the index position.

Removeatindex (_:). Deletes a character at the index location.

RemoveRange (_:). Deletes a string within the specified range.

Replacerange (_:, with:string). Replaces a string in a specified range with a string or character.

Code:

var str = "Swift"

Print ("Raw string: \ (str)")

Str.splice ("Objective-c and". Characters, AtIndex:str.startIndex)

Print ("After inserting string: \ (str)")

Str.insert (".", AtIndex:str.endIndex)

Print ("insert. Word specifier: \ (str)")

Str.removeatindex (Str.endIndex.predecessor ())

Print ("delete. Word specifier: \ (str)")

var startIndex = Str.startindex

var endIndex = advance (StartIndex, 9)

var range = Startindex...endindex

Str.removerange (Range)

Print ("After delete range: \ (str)")

StartIndex = Str.startindex

EndIndex = advance (startIndex, 0)

Range = Startindex...endindex

Str.replacerange (range, with: "C + +")

Print ("Replace range: \ (str)")

Output Result:

Original string: Swift

After inserting a string: Objective-c and Swift

Insert. Word specifier: objective-c and Swift.

Delete. Word specifier: objective-c and Swift

After the scope is deleted: C and Swift

After replace range: C + + and Swift

-- Note the conversion between numeric types

In other languages such as C, Objective-c, and Java, there are two ways to convert integers:

1, from the small range number to the large range number conversion is automatic;
2, from the large-scale number to the small range number needs to be forced type conversion, it is possible to cause the loss of data precision.

In Swift, these two methods do not work, and need to be explicitly converted through some functions, the code is as follows:

Let Historyscore:uint8 = 90

Let englishscore:uint16 = 130

Let Totalscore = Historyscore + englishscore//Error

The program will have a compilation error because Historyscore is a UInt8 type, and Englishscore is a UInt16 type and cannot be converted between them.

Two methods of conversion:

· One is to convert the UInt8 historyscore to the UInt16 type. This conversion is safe because it is converted from a small range to a large range number.

Code: Let Totalscore = UInt16 (historyscore) + Englishscore//is the correct conversion method.

• The other is to convert the UInt16 englishscore to the UInt8 type. Because it is converted from a large range to a small range number, this conversion is unsafe, and if the number of conversions is larger it can result in loss of precision.

Code: Let Totalscore = Historyscore + UInt8 (englishscore)//is the correct conversion method.

Conversions between integral and floating-point types are similar to conversions between integral types:

Let historyscore:float = 90.6

Let englishscore:uint16 = 130

Let Totalscore = Historyscore + englishscore//Error

Let Totalscore = Historyscore + Float (englishscore)//correct, secure

Let Totalscore = UInt16 (historyscore) + englishscore//correct, decimals truncated

-- Dictionary Collection

The Swift dictionary represents a very complex collection that allows elements to be accessed by a key. A dictionary is a set of two parts, one is a set of key (key), and the other is a collection of values (value). A key collection cannot have duplicate elements, and a collection of values can be duplicated, and the keys and values are paired.
Dictionary Declaration and initialization
The Swift dictionary type is dictionary and is also a generic collection.
You can use one of the following statements when declaring a dictionary type.

var  string >
var string]

The dictionary of the Declaration needs to be initialized to be used, and the dictionary type is often initialized at the same time as the declaration.


= [
102 " Zhang San" , John Doe " 109 " Harry "]
var studentDictionary2 = [102 "  Zhang San" , John Doe "   109  " Harry "]
let studentDictionary3 = [102 "  Zhang San" , John Doe "   109  " Harry "]

Dictionary traversal
The dictionary traversal process can traverse only the collection of values, or only the collection of keys, or it can traverse at the same time. These traversal processes are implemented through the for-in loop.

var  studentDictionary = [ 102 "  Zhang San" , John Doe "   109  " Harry "]
Print ( "---traversal key---" for in )
studentDictionary.keys {  
print ( "study number: \ (StudentID)")
}
Print ( "---traverse value---" For in )
studentDictionary.values {
print ( student: \ (studentname))
}
Print ( "---traversal key: Value---" For in )
studentDictionary {
print ( "\ (StudentID): \ (studentname)")
}

The results of the operation are as follows:
---traversal key---
Study No.: 105
Study No.: 102
Study No.: 109
---traversal value---
Student: John Doe
Student: Zhang San
Student: Harry
---traversal key: Value---
105: John Doe
102: Zhang San
109: Harry

--swift collection of arrays in

An array is a series of ordered sets of elements of the same type. The collection elements in the array are ordered and can recur.

You can use one of the following statements when declaring an array type.

var studentlist1:array<string>

var studentList2: [String]

The declared array is not yet available and needs to be initialized, and the array type is often initialized at the same time as the declaration. The sample code is as follows:

var studentlist1:array<string> = ["Zhang San", "John Doe", "Harry", "Zhao Liu"]

var studentList2: [String] = ["Zhang San", "John Doe", "Harry", "Zhao Liu"]

Let studentList3: [String] = ["Zhang San", "John Doe", "Harry", "Zhao Liu"]

var studentList4 = [String] ()

Array traversal

The most common operation of an array is traversal, which is to take each element of the array out and manipulate or calculate it. The entire traversal process is inseparable from the loop, and the for-in loop can be used.

var studentlist: [String] = ["Zhang San", "John Doe", "Harry"]

For item in Studentlist {

Print (item)

}

For (index, value) in Studentlist.enumerate () {

Print ("Item \ (index + 1): \ (value)")

}

The results of the operation are as follows:

Tom

John doe

Harry

Item 1: Zhang San

Item 2: John Doe

Item 3: Harry

-- function Parameter Passing

The syntax format for the function is as follows:

Func function name (parameter list), return value type {

Statement Group

return value

}

Function: The keyword is func.

Multiple parameter lists can be separated by commas (,), or without parameters.

Use the arrow "-" to indicate the return value type. The return value has a single value and multiple values. If the function does not return a value, the return value type section can be omitted.

If the function has a return value, the return statement needs to be used at the end of the function body, or the return statement can be omitted in the function body if there is no return value.

The function definition sample code is as follows:

Func Rectanglearea (width:double, height:double), Double {

Let area = width * height

Return area

}

Print ("Area of 320x480 rectangle: \ (Rectanglearea (320,height:480))")

Here are a few different forms of passing parameters.

1. Using external parameter names

Provide a name for each parameter that can be used outside the function, called the external parameter name, and modify the Rectanglearea function as follows:

Func Rectanglearea (W width:double, H height:double), Double {

Let area = width * height

Return area

}

Give an "external parameter name" before the local parameter name, separated by a space. The W and h in the definition code are the external parameter names. The calling code is as follows:

Print ("Area of 320x480 rectangle: \ (Rectanglearea (w:320,h:480))")

If we provide an external parameter name, the external parameter name must be used when the function is called, so W and H cannot be omitted.

2. Omitting the name of an external parameter

Swift 2.0 provides the possibility of omitting the external parameter name, which, when defining a function, uses an underscore (_) to represent the external argument name, and the sample code is as follows:

Func Rectanglearea (width:double, _ height:double), Double {

Let area = width * height

Return area

}

This allows the function to omit the external parameter name when it is called, and the code is as follows:

Print ("Area of 320x480 rectangle: \ (Rectanglearea (320,480))")

When defining a function, the first parameter does not need to use an underscore (_), the default first parameter name is omitted, and the other parameter names need to be omitted to use the underscore (_) symbol.

3. Parameter Default value

When defining a function, you can set a default value for the parameter, which can be ignored when the function is called. Look at one of the following examples:

Func Makecoffee (type:string = "Cappuccino"), String {

Return "make a cup \ (type) of coffee." "

}

When called, the default value is used if the caller does not pass the parameter. The calling code is as follows:

Let coffee1= makecoffee ("latte")

Let coffee2= Makecoffee ()

The final output results are as follows:

Make a cup of latte.

Make a cappuccino cup of coffee.

4. Variable parameters

The number of arguments to a function in Swift can vary, and it can accept an indeterminate number of input type parameters, which have the same type. We can do this by adding (...) after the parameter type name. ) to indicate that this is a mutable parameter.

Let's look at an example:

Func sum (numbers:double ...), Double {

var total:double = 0

For number in numbers {

Total + = number

}

Return Total

}

The following is a two-time call to the SUM function code:

Sum (100.0, 20, 30)

SUM (30, 80)

You can see that the number of arguments passed each time is different.

This is the basic note that I am learning swift to organize, hope to give more just learn iOS developer to bring help, here bloggers thank you very much for your support!

Please refer to my next blog post for more information. And then in the ongoing update ...

Learn Swift notes starting from 0 (i)

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.