Swift Learning-01-Basic Section

Source: Internet
Author: User

Print ("The World, Hello")

var myvariable = 42

myvariable = 50

Let myconstant = 42

Let Implicitinteger = 70

Let fffffff = 70.0

Let exnfjenb:double = 80

Let Changliang:float = 4

var frewf:double = 5

Print (Changliang)

Let label = "You Oh Good"

Let width = 94

Let Widthlabel = label + String (width)

Let Label2 = "1234565"

Let Heught:int = 88

Let all = String (heught) + Label2

Let apples = 3

Let oranges = 5

Let Applecount = "I has \ (apples) apples"

Let Fruitcount = "I has \ (oranges) oranges"

Print (Fruitcount)

Let fudina:double = 402.0840000

Let hellostr = "Nihao de \ (Fudina) Nihao"

Print (HELLOSTR)

var shoplist = ["Apple", "oranges", "banage", "Blueanj"]

SHOPLIST[1] = "BBBBBB"

Shoplist. RemoveAll ()

If Shoplist.count > 2 {

Print (shoplist[1])

}else{

Print ("Array is empty")

}

var dictionary = ["AAA": "AAA", "BBB": "BBB"]

var emptyarray = [String] ()

Let individualscores = [12,23,34,45,56]

var teamscores = 0

For score in Individualscores {

If score > 20 {

Teamscores + = 3

}else{

Teamscores + = 1

}

}

Print (Teamscores)

The condition must be a bool value in the IF statement, which means that the judgment will not be invisible compared to 0

Together, you can use if and let to handle the case where the value is true, and these values will be represented by an optional value

An optional value is either a specific value or nil to indicate that the value is missing, and a question mark is appended to the type to mark the variable's value as optional

var optionalname:string? = "John Appleseed"

Optionalname = Nil

var greeting = "Hello!"

If let name = optionalname {

Greeting = "Hello, \ (name)"

}else{

Greeting = "hello!, (Dulusi)"

}

Print (greeting)

If the optional value of the variable is nil, the condition evaluates to false, the code in the curly braces is skipped, and if it is not nil, the value is unpacked and assigned to the constant behind let, so the value can be used in the code.

There is also a way to process an optional value by using the?? operator to provide a default value, if the optional value is missing, you can use the default value instead

Let nickname:string? = "Dingzhiije"

Let fullname:string = "Dingzhijie"

Let MyName = ' My name is \ (nickname?? FullName) "

Print (MyName)

Switch supports any type of data and various comparison operations-not just integers and test equality

Let Vegetrabel = "red pepper"

Switch Vegetrabel {

Case "Red pepper":

Print ("Red")

Case "BLACK":

Print ("Black")

Default

Print ("No")

}

After running the switch in Swift, the program exits the switch statement and does not run down, so there is no need to write a break after each clause;

Let interestingnumbers = [

"Prime": [2,3,5,7,11,13],

"Fibonacci": [1,1,2,3,5,8],

"Square": [1,4,9,16,25]

]

Traverse Dictionary

var largest = 0

var largestkey:string = ""

for (kind,numbers) in Interestingnumbers {

For number in numbers {

If number > largest {

largest = number;

Largestkey = Kind

}

}

}

Print (largest)

Print (Largestkey)

var num = 0

var addnum = 0

While Num < 101 {

Addnum = addnum + num

num + = 1

}

Print (Addnum)

Loop conditions can also be looped at the end, at least once

Repeat loop statements

var m = 2

Repeat {//repeat

m = m * 2

} While M < 100

Print (m)

Can be used in recycling: < to represent the range

var total = 0

For i in 0.. < 4 {

Total + = 1

Print (i)

}

A.. The range of < b is greater than or equal to a, but less than B

A ... the range of B is greater than or equal to a, and less than or equal to B

This is because ... < creates a range that does not contain an upper bound, but ... The created range contains an upper bound

Use Func to declare a function, use the name and arguments to invoke the function, and so on to specify the type of the function's return value

Func Green (person:string, day:string), String {

return "Hello \ (person), today was \ (day)"

}

Print (Person: "Houdecheng", Day: "2017-5-5"))

Func Eat (person:string, eatwhat:string), String {

return "Hello, \ (person), my today wat\ (eatwhat)"

}

Print (Eat (person: "Houdehcneg", Eatwhat: "Danchaofan"))

By default, functions use their parameter names as labels for their parameters, you can customize the parameter labels before the parameter names, or use _ to indicate that the parameter labels are not used

Func Ceshi (_ Person:string,on day:string), string{

return "Hello, \ (person), today was \ (day)"

}

Print (Ceshi ("Houdehceg", On: "2017-5-5"))

Use tuples to let functions return multiple values, and the elements of tuples can be represented by names or numbers

Func Yuanzuceshi (scores: [Int]), (Min:int,max:int, sum:string) {

var min = scores[0]

var max = scores[0]

var sum = 0

For score in scores {

If score > Max {

Max = Score

}else If score < min{

Min = Score

}

sum + = score;

}

Let sumstr:string = String (sum)

Return (MIN,MAX,SUMSTR)

}

Print (Yuanzuceshi (scores: [15,54,45,54,78,15,6,98]))

Functions can have a variable number of parameters, which behave as an array in the function

Func Kebiancanshu (Numbers:int ...), Double {

var sum = 0

For I in numbers {

sum + = i

}

Let pingjunzhi:double = Double (sum)/double (Numbers.count)

Return Pingjunzhi

}

Print (Kebiancanshu (numbers:4,3,5,6))

Functions can be nested, and nested functions can access variables of the outer function you can use nested functions to refactor a function that is too long or too complex

Func Returnfifteen ()-int{

var y = 10

Func Add () {

Y + = 5

}

Add ()

Return y

}

Print (Returnfifteen ())

The function is the first class type, which means that the function can be the return value of another function.

Func AddOne (number:int,str:string), int{

return Int (str)! + Number

}

Func Makeincrmenter (), ((int,string), Int) {

Return AddOne (number:str:)

}

var increment = Makeincrmenter ()

Print (Increment (88, "44"))

Function can also be passed as a parameter to another function

Func hasanymatches (list: [int], condition: (int), Bool), bool{

For item in list {

If condition (item) {

return True

}

}

return False

}

Func Lessthanten (number:int), Bool {

Return number < 10

}

Let numbers = [20,19,7,12]

Let dictionary2:dictionary = ["1": 45, "2": 43]

Print (Hasanymatches (list:numbers, Condition:lessthanten (number:)))

A function is actually a special kind of closure that is a code that can be called after a period of time. The code in the closure can access the variables and functions that are available in the scope created by the closure, even if the closure is executed in a different scope-you can use {} to create an anonymous closure using the in Separating the parameter and return value types from the closure function body

Print (Numbers.map {(number:int), Int in

Let result = 3 * number

return result

})

There are many ways to create a cleaner closure, and if a type of closure is known, such as a callback function, you can ignore the type and return value of the parameter, and a single statement closure will return the value of its statement as the return value

Let Mappednumbers = Numbers.map ({number in 3 * number})

Print (mappednumbers)

Let Mappendnumbers = numbers.map {(number:int), Int in

Let result = 3 * number

return result

}

Print (mappendnumbers)

Parameters can be referenced by the position of the parameter rather than by the name of the parameter-this method is very useful in very short closures, and when a closure is passed to the function as the last argument, he can be directly behind the parentheses, and when a closure is the only parameter passed to the function, you can completely ignore the parentheses

Let Sortednumbers = numbers.sorted {(A, B)-Bool in

A > B

}

Print (sortednumbers)

Sort of dictionary

Let dicsorted = dictionary2.sorted {(A, B)-Bool in

A.value > B.value

}

Print (dicsorted)

Objects and classes

Create a class with the class name. The only difference between a declaration and a variable declaration of a property in a class is that their context is a class, as well as the method kernel function declaration.

Class Shape {

var numberofsides = 0

Func simpledescription (), String {

Return "A shape with \ (numberofsides) sides."

}

}

To create an instance of a class, enclose the class name with parentheses, and use point syntax to access the instance's properties and methods

var shape = shape ()

Shape.numberofsides = 7

Print (Shape.simpledescription ())

Class myday{

Let day = "May 5, 2017"

Func Prienday (day:string), String {

Return "Today is \ (day)"

}

}

var mydays = Myday.init ()

Print (Mydays.prienday (day:mydays.day))

This version of Shape lacks something important, a constructor to initialize the instance, and init to create a constructor

Class namedshape{

var numberofsides:int = 0

var name:string

Init (name:string) {

Self.name = Name

}

Func simpledecription (), String {

Return "A shape with \ (numberofsides) \ (name) sides"

}

}

var nameshpe = namedshape.init (name: "Houdehcneg")

Print (Nameshpe.simpledecription ())

Note that self is used to differentiate instance variables, and when you create them, like passing in a function parameter, you rub the class with the constructor's arguments, and each property needs to be assigned-whether by declaring (for example, Numberofsides) or by a constructor (for example, name)

If you need to do some cleanup before deleting the object, create a destructor using Deinit

Subclasses are defined by adding the name of the parent class after their class name, separated by colons, and creating classes without a standard class, so you can ignore the parent class

Subclass if you need to override the method of the parent class, you need to use the override tag--if you do not add override to override the parent class, the method Editor will error, and the editor will also detect if the override tag's method is actually in the parent class

Class square:namedshape{

var sidelength:double

Init (sidelength:double,name:string) {

Self.sidelength = Sidelength;

Super.init (Name:name)

Numberofsides = 4

}

Func area (), Double {

Return sidelength * sidelength

}

Override Func Simpledecription (), String {

Return "A squre with side of length \ (sidelength) \ (numberofsides)"

}

}

Let test = Square.init (sidelength:5.2, Name: "My Test Squre")

Print (Test.area ())

Print (Test.simpledecription ())

Class circle:namedshape{

var banjing:double

Init (banjing:double,name:string) {

self.banjing = banjing

Super.init (Name:name)

}

Func area (), Double {

Return self.banjing

}

Override Func Simpledecription (), String {

Return "\ (banjing), \ (numberofsides), \ (name)"

}

}

var circle = circle.init (banjing:2.0, Name: "Dinngzhijie")

Print (Circle.area ())

Print (Circle.simpledecription ())

Swift Learning-01-Basic Section

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.