The Swift Introductory Tutorial: Simple basic syntax

Source: Internet
Author: User
Tags arrays character set data structures numeric lowercase modifier readable


I. Basic grammar:

Swift is a new language for the development of IOS and OS X applications. However, if you have a C or objective-c development experience, you will find that many of Swift's content is familiar to you.


Swift's type is based on C and objective-c, int is integral; double and float are floating-point; bool is Boolean; string is a string. Swift also has two useful collection types, array and dictionary, please refer to the collection type.

Like the C language, Swift uses variables to store and correlate values through variable names. In Swift, variables with immutable values are widely used, they are constants, and are more powerful than the C-language constants. In Swift, if you're dealing with a value that doesn't need to be changed, using constants can make your code safer and more expressive of your intentions.

In addition to the familiar types, Swift also adds types such as tuples (Tuple) that are not in objective-c. Tuples allow you to create or pass a set of data, such as the return value of a function, you can use a tuple to return multiple values.

Swift has also added an optional (Optional) type for handling values that are missing. Optional means "There is a value there, and it equals 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, which is an important part of Swift's many powerful features.

Swift is a type-safe language, and optional is a good example. Swift can give you a clear idea of the type of value. If your code expects to get a string, type safety will prevent you from accidentally passing in an int. You can find and fix bugs early in the development phase.

Variables and constants:
Constants and variables associate a name (such as maximumnumberofloginattempts or welcomemessage) with a value of a specified type (such as the number 10 or the string "Hello"). The value of a constant cannot be changed once it is set, and the value of the variable can be changed arbitrarily.


Declaring constants and variables:

Constants and variables must be declared before use, with let to declare constants, and VAR to declare variables. The following example shows how to use constants and variables to record the number of times a user attempts to log on:


--------------------------------------------------------------------------------

Let maximumnumberofloginattempts = 10

var currentloginattempt = 0


--------------------------------------------------------------------------------

numeric literal:

The whole number of facets can be written:

A decimal number with no prefix

A binary number with a prefix of 0b

A octal number with a prefix of 0o

A hexadecimal number with a prefix of 0x

The decimal value of all the following integer literals is 17:

Let Decimalinteger = 17

Let Binaryinteger = 0b10001//binary 17

Let Octalinteger = 0o21//Eight 17

Let Hexadecimalinteger = 0x11//16 17

Floating-point literals can be decimal (without a prefix) or hexadecimal (prefixed by 0x). You must have at least one decimal digit (or hexadecimal number) on both sides of the decimal point. Floating-point literals also have an optional index (exponent) that is specified in decimal floating-point numbers by uppercase or lowercase e, in hexadecimal floating-point numbers by uppercase or lowercase p.

If the exponent of a decimal number is exp, that number is equivalent to the product of cardinality and $10^{exp}$:

1.25e2 means $1.25x10^{2}$, equal to 125.0.

1.25e-2 means $1.25x10^{-2}$, equal to 0.0125.

If the exponent of a hexadecimal number is exp, that number is equivalent to the product of cardinality and $2^{exp}$:

0XFP2 says $15x2^{2}$, equal to 60.0.

0xfp-2 says $15x2^{-2}$, equal to 3.75.

The following floating-point literals are equal to 12.1875 of the decimal number:

Let decimaldouble = 12.1875

Let exponentdouble = 1.21875e1

Let hexadecimaldouble = 0xc.3p0

Numeric class literals can include additional formatting to enhance readability. Both integers and floating-point numbers can add an additional 0 and contain underscores that do not affect literal content:


--------------------------------------------------------------------------------

Let paddeddouble = 000123.456

Let onemillion = 1_000_000

Let justoveronemillion = 1_000_000.000_000_1


--------------------------------------------------------------------------------

META Group
Tuples (tuples) combine multiple values into a single compound value. The values within a tuple can make any type, and do not require the same type.

In the following example, (404, "not Found") is a tuple that describes the HTTP status code (HTTP state code). The HTTP status code is a special value that the Web server returns when you request a Web page. If the page you requested does not exist, it returns a 404 Not Found status code.

Let Http404error = (404, "not Found")//Http404error type (Int, String), value is (404, "not Found")

(404, "not Found") the tuple combines an int value and a string value to represent two parts of the HTTP status code: A number and a human-readable description. This tuple can be described as "a tuple of type (INT, String)".

You can combine any sequence of types into a tuple, which can contain all types. As long as you want, you can create a tuple of types (int, int, int) or (String, Bool) or any other group you want.

You can decompose the contents of a tuple (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 isn't Found"

If you need only part of a tuple value, you can use the underscore (_) to mark the part you want to ignore when you decompose:

Let (Justthestatuscode, _) = Http404error

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

Output "The status code is 404"

In addition, you can access a single element in a tuple by subscript, with the subscript starting 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 isn't Found"

You can name a single element when you define a tuple:

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

After naming the elements in a tuple, you can get 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 returning values as functions. A function used to get a Web page might return an (Int, String) tuple to describe whether or not success was obtained. Compared to a value that can return only one type, a tuple that contains two different types of values can make the return information of the function more useful. Refer to [function parameters and return values (06_functions.html#function_parameters_and_return_values).

Note: Tuples are useful when organizing values temporarily, 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 tuple. Please refer to class and struct body.

Two, swif operator

A. Cycle
The common loops are: for/while/do while

1.for Loop
For-loop writing in 1.1 oc

for (int i = 0; i < i++) {

}
The wording of 1.2 swift

Interval Traversal 0..<10 0...9

For I in 0..<10 {
Print (i)
}

For I in 0...9 {
Print (i)
}
If an identifier does not need to be used, then you can use _ to replace the

For _ in 0..<10 {
Print ("Hello World")
}
2.while Loop
The wording of 2.1 oc

int a = 20
while (a) {
}
The wording of 2.2 swift

2.2.1while after () can omit

2.2.2 Not 0 (nil) that is true

var i = 10
While I > 0 {
Print (i)
I-= 1
}
3.do while loop
Difference: no longer use do while--> repeat while
var m = 0
Repeat {
Print (m)
M + 1
While M < 10
Two. String
1. Introduction to Strings
1.1 strings are used very frequently in any development.

The difference between the strings in 1.2OC and Swift

NSString in the case of a string type in OC, the string type in Swift
OC in string @ "", string "" in Swift

1.3 Reasons to use String

A String is a structural body with a higher performance
NSString is an OC object with a slightly worse performance
String supports direct traversal
String provides seamless conversion between string and NSString

2. Definition of string
2.1 Defining immutable strings

Let str = "Hello Swift"
2.2 Defining variable strings

var strm = "Hello World"
STRM = "Hello"
3. Get the length of the string
Get the character set and then get the Count property of the collection

Let length = Str.characters.count
4. Traverse string
For C in Str.characters {
Print (c)
}
5. Concatenation of strings
5.1 Stitching between strings

Let str1 = "Hello"
Let str2 = "the World"
Let STR3 = str1 + str2
5.2 Stitching between strings and other identifiers
Let name = "LGP"
Let-age = 18
Let height = 1.98
Let infostr = ' My name is ' (name), age was (age), ' is ' (height) '

5.3 String Formatting
such as time: 03:04 If the display 3:4 is not good. So you need to format

Let min = 3
Let second = 4
Let Timestr = String (format: "%02d:%02d", arguments: [min, second])
6. Interception of strings
The 6.1 simple way is to turn a string into nsstring to use the
After the identifier is added: as NSString can

1. Mode one: Convert string type to NSString type, then intercept

(URLString as NSString)--> NSString
Let Header = (urlstring as NSString). Substringtoindex (3)
Let footer = (urlstring as NSString). Substringfromindex (10)
Let range = Nsmakerange (4, 5)
Let middle = (urlstring as NSString). Substringwithrange (Range)
A special interception mode is provided in 6.2Swift
The way is very troublesome
Index creation is more troublesome

2. Mode two: Swift native way to intercept

Let Headerindex = UrlString.startIndex.advancedBy (3)
Let Header1 = Urlstring.substringtoindex (Headerindex)

Let Footerindex = UrlString.endIndex.advancedBy (-3)
Let Footer1 = Urlstring.substringfromindex (Footerindex)

Let Range1 = Headerindex.advancedby (1). <footerindex.advancedby (-1)
Let Middle1 = Urlstring.substringwithrange (range1)
Three. Use of arrays
1. Introduction to Arrays
A 1.1 array is a sequence of ordered sets of elements of the same type

The collection elements in the 1.2 array are ordered and can recur

1.3 The array in Swift
Swift array type is array and is a generic collection

2. Initialization of arrays
2.1 Defining an immutable group, using the Let modifier
Note: The immutable group must be initialized at the same time as it is defined, otherwise it is meaningless

Let array = ["Why", "YZ"]
2.2 Define a variable array, using the Var modifier
Note: An array is a generic collection, and you must make the type of the element that is stored in that array

Basic wording
var Arraym = array<string> ()
Simple wording
var arraym = [String] ()
3. Basic operations on variable arrays (add-up check)
3.1 Adding elements

Arraym.append ("LJP")
3.2 Deleting elements

Let RemoveItem = Arraym.removeatindex (1) returns the element to which the value is deleted
Arraym.removeall ()
3.3 Modifying elements

Arraym[0] = "why"
3.4 Find Element (get element based on subscript)

Let item = arraym[0]
4. Traversal of arrays
4.1 Traversing the subscript value

For I in 0..<array.count {
Print (Array[i])
}
4.2 Traversal elements

For name in array {
Print (name)
}
4.3 traversing subscript values and elements

For (index, name) in Array.enumerate () {
Print (index)
Print (name)
}
5. Merging of arrays
Arrays of the same type can be added together for merging
Variable groups and immutable arrays can also be merged

Let array1 = ["Why", "YZ"]
Let array2 = ["LMJ", "LNJ"]
Let Resultarray = Array1 + array2
Four. Use of dictionaries
1. Introduction to the Dictionary
1.1 Dictionaries allow access to elements by a key

The 1.2 dictionary is composed of two parts, one is the key (key) set, and the other is a collection of values (value).

A 1.3-key collection cannot have duplicate elements, and a set of values can be duplicated, with keys and values appearing in pairs.

A dictionary in 1.4Swift
The Swift dictionary type is dictionary and is also a generic collection

2. Initialization of the Dictionary
2.1 Defining immutable dictionaries, using let decoration
Note: Immutable dictionaries are initialized at the same time as they are defined, otherwise there is no meaning
The system will determine whether the [] is an array or a dictionary based on whether the [] is a key-value pair or a single element.

Let dict = ["Name": "Why", "Age": "," height ": 1.88]
2.2 Defining a variable dictionary, using the Var modifier
Note: The dictionary is a generic collection, and you must make the type of the element that is stored in the array

Basic wording
var DICTM = dictionary<string, nsobject> ()
Simple wording
var DICTM = [String:nsobject] ()//Common
3. The basic operation of the variable dictionary (increase the check)
3.1 Adding elements

Dictm.updatevalue ("Why", Forkey: "Name")
3.2 Deleting elements

Dictm.removevalueforkey ("Age")
3.3 Modifying elements

If the original does not have a corresponding key/value, then add the key value pair
If the original already has a corresponding key/value, then directly modify

Dictm.updatevalue ("1.77", Forkey: "Height")
dictm["Name" = "Why"
3.4 Find Element (get Element)

Let item = dictm["Name"]
4. The Dictionary traversal
4.1 Traversing all key in the dictionary

For key in Dict.keys {
Print (key)
}
4.2 Traversing all the value in the dictionary

For value in Dict.values {
Print (value)
}
4.3 Traversing all the key/value in the dictionary

For (key, value) in Dict {
Print (key)
Print (value)
}
5. Merging of dictionaries
Dictionaries of the same type can not be added together for merging
You can change one of the dictionaries to variable, iterate through the dictionary, and add one or more elements to another immutable dictionary.

Let Dict1 = [' name ': ' Why ', ' age ': 18]
var dict2 = ["height": 1.88, "Phonenum": "+86 110"]

For (key, value) in Dict1 {
Dict2[key] = value
}
Five. Use of tuples
1. Introduction to the META Group
The 1.1-tuple is unique to Swift, and there are no related types in OC

1.2 What is it?
1.2.1 It is a data structure that is widely used in mathematics.
1.2.2 is similar to an array or a dictionary
1.2.3 can be used to define a set of data
1.2.4 data that makes up a tuple type can be called an "element"

2. Why is a tuple used?
If a dictionary or array holds multiple data types, then the data type taken from the dictionary array is nsobject, which is inconvenient when used, and is converted to the true type first.

Tuples save a variety of data types, taken out is the true type of the data, without the need for conversion can be directly used

3. Definition of tuples
Let Infotuple = ("Why", 18, 1.88, "+86 110")
Using tuples to describe a person's information
("1001", "John", 30, 90)
Adds an element name to an element, which can then be accessed by an element name
(ID: "1001", Name: "John", English_score:30, chinese_score:90)

Constructor Basics

A constructor is a special function that is used primarily to initialize an object when it is created, to set an initial value for an object member variable, the constructor in OC is Initwithxxx, and in Swift because the function overload is supported, all constructors are init

The function of a constructor

Allocate Space alloc
Set Initial value init
Required Attributes

Customizing the Person Object
Class Person:nsobject {

Name
var name:string
Age
var age:int
}
Prompt error class ' person ' has no initializers-> ' person ' class has no instantiation s

Reason: If a required attribute is defined in a class, you must allocate space for these required attributes through the constructor and set the initial value

Overriding the constructor of a parent class
' Overriding ' The constructor of the parent class
Override Init () {

}
Prompt error property ' Self.name ' not initialized at implicitly generated super.init call-> attribute ' Self.name ' not implicitly generated Super.ini T is initialized before calling

Manually add Super.init () call
' Overriding ' The constructor of the parent class
Override Init () {
Super.init ()
}
Prompt error property ' Self.name ' not initialized at Super.init call-> attribute ' Self.name ' was not initialized before Super.init invocation

Set an initial value for a required property
' Overriding ' The constructor of the parent class
Override Init () {
Name = "John"
Age = 18

Super.init ()
}
Summary

A Optional property must set an initial value in the constructor to ensure that the property is initialized correctly when the object is instantiated
Before calling the parent class constructor, you must ensure that the properties of this class have been initialized
Constructors in Swift do not need to write Func
Constructors for subclasses

When you customize a subclass, you need to set the initial value in the constructor, first for the property defined by this class
Then call the constructor of the parent class and initialize the properties defined in the parent class
Student class
Class Student:person {

School Number
var no:string

Override Init () {
No = "001"

Super.init ()
}
}
Summary

The constructor of this class is called first to initialize the properties of this class
The constructor of the parent class is then invoked to initialize the properties of the parent class
Xcode 7 Beta 5, the constructor of the parent class is invoked automatically, writing super.init () is strongly recommended, keeping the code execution Trail readable
Super.init () must be placed after the initialization of this class property to ensure that all of the properties of this class are initialized
Optional Property

Set the object property type to Optional
Class Person:nsobject {
Name
var name:string?
Age
var age:int?
}
Optional properties do not need to set the initial value, the default initial value is nil
Optional attributes are allocated space when setting numeric values, and are deferred allocation space, more consistent with the principle of delay creation in mobile development
Overloaded constructors

function overloading is supported in Swift, same function name, different parameter type
' Overloaded ' constructors
///
-Parameter name: Name
-Parameter Age: ages
///
-Returns:person Object
Init (name:string, Age:int) {
Self.name = Name
Self.age = Age

Super.init ()
}
Attention matters

If the constructor is overloaded, but the default constructor init () is not implemented, the default constructor is no longer provided by the system
Cause, when instantiating an object, you must allocate space and set the initial value through the constructor for the object property, and the default init () cannot complete the assignment space and set the initial value for a class that has a required argument
To adjust the constructor of a subclass

Overriding the constructor of a parent class
' Overriding ' The parent class constructor
///
-Parameter name: Name
-Parameter Age: ages
///
-Returns:student Object
Override Init (name:string, Age:int) {
No = "002"

Super.init (Name:name, Age:age)
}
Overloaded constructors
' Overloaded ' constructors
///
-Parameter name: Name
-Parameter Age: ages
-Parameter No: School number
///
-Returns:student Object
Init (name:string, Age:int, no:string) {
self.no = No

Super.init (Name:name, Age:age)
}
Note: If an overloaded constructor, you must be super to complete the initialization of the parent class property

Overloading and overriding

Overload, the function name is the same, parameter name/parameter type/parameter count is different
Overloaded functions are not only limited to constructors
Function overload is an important symbol of object-oriented programming language
Function overloading simplifies the memory of programmers
OC does not support function overloading, the alternative of OC is withxxx ...
Overrides, the subclass needs to be extended on the basis of the parent class's owning method, requiring the override keyword

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.