Introduction to Swift Fundamentals (based on Swift2.0)

Source: Internet
Author: User
Tags closure closure definition naming convention

: Playground-noun:a place where people can play

Import UIKit

There is no need to set the main function entry in Swift, and the compiler will automatically set the entry for the program in the global function, and you can write the SWIFT code without using the ";" As the end flag of a statement

var str = "Hello, playground"

var str1 = "Hello, lile"

Print ("Hello world!")//Swift2.0 Use OUTPUT statement (also available in Swift1.2 version)

Output statements used by println ("Hello world!")//Swift1.2 and previous versions

In Swift, we do not need to give the data types of constants and variables, the compiler will automatically speculate on its data type based on subsequent assignments, and in some cases we need to assign a constant or variable data type, at which point we only need to add ":" after the constant/variable name.

-----------Constant-----------

Define using the Let keyword

Definition form 1:let constant name = constant value

Let A = 10

Definition form 2:let constant name: Data type = constant value

Let B:int8 = 11

------------variable-------------

Define using the var keyword

Definition form: var variable name = variable Value

var C = 12

Definition form: var variable name: Data type = variable value

var d:float = 13

The SWIFT constant/variable naming convention is more open, almost all Unicode encodings are supported, and we can even name it in Chinese

var haha = "hehe"

Print (haha)

Operation does not support implicit conversion of data types in swift, the conversion must be displayed

var sum = Float (c) + D

Print ("hehe is" + "\ (c)")

Print ("Hehe is \ (c)")

------------tuple-------------

var person = (name: "Zhang San", age:99, Sex: "Male")

person.0

Person.1

Person.2

Person.name = "John Doe"

Person.age

Person.sex

------------Array-------------

The array in swift requires that the data type of each element must be uniform and automatically converted to an array in OC if the data type is not uniform

Let defines immutable groups, VAR defines mutable arrays

Definition form: Let/var array name: [array element type] = value of array ps: "[array element type]" can omit do not write

Define an empty array

var emptyarray: [String] = [string] ()

var blacklist = ["Zhang San", "Bai Hao"]

Blacklist. Append ("John Doe")

Blacklist. Insert ("Gerdford", Atindex:2)

Blacklist. Insert ("Jin Xin Liang", atindex:2)

Blacklist. Removeatindex (2)

Take a range

0...2 represents a closed interval of 0 to 2

Blacklist [0...2]

0..<2 represents 0 to 2 left closed right open interval

Blacklist [0..<2]

------------Dictionary-------------

In Swift, the key in the dictionary must be a uniform type, value must be of a uniform type, and key and value can be of different types, and if they are stored, they will automatically be converted to a dictionary in OC.

Create an empty Dictionary

Form 1: (recommended)

var emptyDic1 = [String:int] ()

Form 2:

var emptyDic2 = dictionary<string, int> ()

var persondic = ["Age": One, "num": 99]

Value: can be obtained directly by key, and the notation is similar to the literal in OC

Persondic["Age"]

Change: Remove the corresponding value directly to change the value of the operation

Persondic["age"] = 22;

Add: If key does not exist, the key value pair will be appended directly to the dictionary

persondic["number"] = 10

Delete: Delete the corresponding key value pair by key value

Persondic.removevalueforkey ("Age")

Persondic

------------If statement-------------

If the condition requirement must be a Boolean expression, that is, the previous familiar if (variable) notation, in Swift no longer implicitly converted to a Boolean value, in addition, if the judgment condition can not write parentheses

If 0 = = a {

Print (a)

} else if 1 = = a {

Print (a)

} else {

Print (a)

}

------------Cycle-------------

var count = 10

While Count > 5 {

count--

}

Repeat-while (PS: equivalent to Do-while)

Repeat {

count--;

} while Count > 0

/*

Swift 1.2 notation

do {

count--;

} while Count > 0

*/

For loop

for var i = 0; I < 10; i++ {

Print (i)

}

Var?? = ["??", "??", "??", "??", "??", "??", "??", "??", "??", "??", "??", "Old white"

For-in

For something in?? {

Print (something)

}

For I in 0...10 {

Print (i)

}

------------optional variable (optional variable)-------------

The purpose of an optional variable is that the value of a variable may be empty during use, and we need to make a declaration

var string = "123"

var number:int? = Int (String)

If nil! = number {

Print (number!)//! To split the optional variable, tell the compiler that at this point I'm sure it must have a value

} else {

Print ("number is nil")

}

The second is to determine if the optional variable is empty, if number is null, the constant n will fail, the code executes the content in else, if number is not NULL, the constant n is initialized successfully, in the execution code corresponding to the condition, you can use N

If let n = number {

Print (n)

} else {

Print ("number is empty")

}

When using optional variables, we may not want to use null values, so we can assign a default value to an optional variable, and when the optional variable is empty, the default value

var string1 = "abc"

var number1:int? = Int (string1)

var finalnumber = number1?? 0

Print (Finalnumber)

Switch

The swithc of switch is optimized, we can not write the parentheses of the selection condition, can not write break (PS: Default we do break operation), if we want to forcibly execute the next case, we need to use the Fallthrough keyword, Required to have default

var casenumber = 0

Switch Casenumber {

Case 0:

Print ("0 selected")

Fallthrough

Case 1:

Print ("1 selected")

Default

Print ("Other selected")

}

The condition of the case can be a string

var casestring = "Old white"

Switch Casestring {

Case "Zhang Tao":

Print ("Tao" selected)

Fallthrough

Case "Old white":

Print ("Old white selected")

Default

Print ("Other selected")

}

The case condition can be a range, and the range can be crossed, and if multiple selection conditions are met at the same time, the first one will be executed, and we can use the "where" keyword to select the matching criteria

var caseNumber1 = 10

Switch CaseNumber1 {

Case 0...5:

Print ("number between 0 and 5")

Case Let x where ten = = x:

Print (x)

Case 4..<11:

Print ("number greater than or equal to 4 less than 11")

Default

Print ("other")

}

The condition of a case can also be a tuple

var point = (10, 20)

Switch Point {

Case (0, 0):

Print ("at Origin")

Case (_, 0):

Print ("on X")

Case (0, _):

Print ("On Y")

Default

Print ("Not on Axis")

}

------------function-------------

Definition form: Func function name (parameter list), return value

Internally accessible parameters are called internal parameters, external calls can be seen when the label is called an external parameter, in Swift2.0, the default first parameter is no external label, the parameters will be automatically generated and internal parameter name of the same external parameters

Define a function that has no parameter and no return value

Func SayHello () {

Print ("Hello")

}

SayHello ()

There are no return values for parameters

Func SayHello (name:string) {

Print ("hehe \ (name)")

}

SayHello ("Old white")

There are parameters with return values

Func sayHello1 (name1:string, name2:string)->string {

Return "hehe," + name1 + name2

}

var result = SayHello1 ("Old White,", Name2: "SB")

We can add the corresponding external label to the parameter, and use the default setting without adding it.

Func SayHello2 (PersonName1 name1:string, PersonName2 name2:string, name3:string)->string {

Return "hehe" + name1 + name2 + name3

}

var result2 = SayHello2 (PersonName1: "Old White", PersonName2: "??", Name3: "SB")

The writing in the Swift1.2

//

Func SayHello2 (PersonName1 name1:string, PersonName2 name2:string, #name3: String)->string {

Return "hehe" + name1 + name2 + name3

//}

var result2 = SayHello2 (PersonName1: "Old White", PersonName2: "??", Name3:??)

Functions with multiple parameters (PS: number of indeterminate parameters)

Func sum (Numbers:int ...) ->int {

var sumresult = 0

For I in numbers {

Sumresult + = i

}

Return Sumresult

}

SUM (1, 2, 3)

var value = 10

Func changevalue (inout num:int) {

num = 20

}

ChangeValue (&value)

var comparenumber = 20

var Numberarray = [3, 46, 5, 17, 25, 36, 48, 59]

Func sortnumbers (Compare:int, numbers: [Int])->[int] {

var resultarray: [int] = [int] ()

For num in numbers {

If num > Comparenumber {

Resultarray.append (num)

}

}

Return resultarray

}

Sortnumbers (Comparenumber, Numbers:numberarray)

------------closure Function-------------

Equivalent to block in OC

Closure declaration: (parameter list)--return value

Closure definition: {(parameter list)--return value in function body}

Func sortnumbersfinish (Compare:int, numbers: [int], CB: (Num1:int, Num2:int)->bool), [int] {

var resultarray = [Int] ()//Create an empty array to receive results that meet the criteria

For num in numbers {//iterate through the incoming array, get each number in the array to make a comparison

If CB (Num1:num, Num2:compare) {//with two parameters and one return value for function parameters

Resultarray.append (num)

}

}

Return resultarray

}

Complete closure function, CB: function parameter with two parameters and one return value

Sortnumbersfinish (Comparenumber, Numbers:numberarray, CB: {num1:int, Num2:int)

Bool

Inch

return NUM1 > Num2

})

You can not write the parameter type of the closure function, the compiler will automatically infer the type of the parameter according to the parameters passed in.

Sortnumbersfinish (Comparenumber, Numbers:numberarray, CB: {(NUM1, num2)->bool in

return NUM1 > Num2

})

The return value type can be not written, and the compiler will use the return value of the last line's expression as the return value of the closure function

Sortnumbersfinish (Comparenumber, Numbers:numberarray, CB: {(NUM1, num2) in

NUM1 > Num2

})

You can not write the declaration of the closure parameter, "$" represents the No. 0 parameter of the closure function, "$" represents the 1th parameter of the closure function

Sortnumbersfinish (Comparenumber, Numbers:numberarray, CB: {$ > $})

This requirement can be further shortened, and ">" represents two numbers for comparison

Sortnumbersfinish (Comparenumber, Numbers:numberarray, CB: >)

Trailing closures (recommended): When the closure function is the last parameter of the function, the closure function can be placed outside the function list

When there is only one closure function parameter in the function argument list, the parentheses of the argument list may not be written: function name {closure function}

Sortnumbersfinish (Comparenumber, Numbers:numberarray) {(NUM1, num2), Bool in

return NUM1 > Num2

}

Structural Body *********************

The struct in Swift is similar to a class, has its own properties and methods, and can even have a constructor (Ps:init), which is very different from the structure in OC.

Different points of structure and class in Swift:

1. Struct is a value type, a class is a reference type (PS: reference type, operation memory itself, is a reference to memory. Value type, copy a new equal value to use)

2. Classes can be inherited, structs cannot be inherited

3. Class has a destructor, the structure is not (PS: The destructor we can understand as an arc under the Dealloc method, you can do the release of resources in the operation)

struct Car {

var brand = "Audi Double Diamond"

Func run () {

Print ("I am \ (brand), I am running!")

}

Constructor (PS: equivalent to the initialization method in OC), if we do not customize the constructor method, the structure realizes for us to generate the constructor method automatically

Init (brand:string) {

Self.brand = Brand

}

}

var MyCar = Car (Brand: "Alto")

Mycar.run ()

struct Point {

var x = 0.0

var y = 0.0

}

struct Size {

var width = 0.0

var height = 0.0

}

struct Rect {

var origin = point ()

var size = size ()

Calculated properties

var Center:point {

get {

Let CenterX = origin.x + size.width * 0.5

Let CenterY = origin.y + size.height * 0.5

Return point (X:centerx, Y:centery)

}

set {

origin.x = newvalue.x-size.width * 0.5

ORIGIN.Y = newvalue.y-size.height * 0.5

}

}

Init (x:double, y:double, width:double, height:double) {

Self.origin = Point (x:x, y:y)

self.size = Size (Width:width, height:height)

}

}

var frame = Rect (x:0, y:0, width:100, height:100)

Frame.center.x

Frame.center.y

Frame.center = Point (x:200, y:100)

Frame.origin.x

Frame.origin.y

Class *********************

The root class is not required in swift, so there can be no inheritance relationship

class People {

var name = ""

var name:string

var age:int?

Init (name:string, Age:int) {

Self.name = Name

Self.age = Age

}

Func SayHello () {

Print ("My name is \ (self.name), I am \ (self.age) years old!")

}

Class method

Class Func Saybyebye () {

Print ("Bye Bye")

}

}

var people = people (name: "haha", age:20)

People.name

People.age

People.sayhello ()

People.saybyebye ()

Class Student:people {

var number = 0

Init (name:string, Age:int, Number:int) {

Self.number = number

Super.init (Name:name, Age:age)

}

Override Func SayHello () {

Print ("My name is \ (self.name), I am \ (self.age) years old!, my number is \ (self.number).")

}

}

Protocol **********************

Protocol A {

Func Sayhehe ()

}

Class Lanoustudent:student, A {

Func Sayhehe () {

Print ("He he old white")

}

}

Introduction to Swift Fundamentals (based on Swift2.0)

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.