Welcome to Swift (Apple's official Swift document translation and annotations III)---11~18 page

Source: Internet
Author: User
Tags case statement define function

In the code above, if the optional value is nil, then the criterion is false, and the code in {} will be ignored, and if the optional value is not nil, the value will be assigned to the constant after the let, and the step-by process will be based on the actual block of code.

The Switch syntax supports any type of data, as well as various comparison operations, and is not limited to integer types.

Let vegetable = "red pepper"

Switch Vegetable {

Case "Celery":

Let vegetablecomment = "Add some raisins and make ants on a log."

Case "cucumber", "watercress":

Let vegetablecomment = "so would make a good tea sandwich."

Case Let X where X.hassuffix ("Pepper"):

Let vegetablecomment = "is it a spicy \ (x)?"

Default

Let vegetablecomment = "everything tastes good in soup."

}

  Experiment//Exercises

  Try removing the default case. What error does you get? Trying to delete the default statement, see or get something wrong?

The switch syntax exits immediately after executing the matching code and no longer executes the subsequent case statements, so you do not have to add a break after each case statement to jump out of switch.

In the for-in syntax, you can access each entry in the dictionary in the form of a key-value pair (that is, traversing the dictionary).

Let interestingnumbers = [

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

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

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

]

var largest = 0

For (kind, numbers) in Interestingnumbers {

For number in numbers {

If number > largest {

largest = number

}

}

}

Largest

  Experiment//Exercises

  ADD another variable to keep track of which kind of number is the largest, as well as what is largest number was. Try adding another variable to track the type of largest, and also see what the value of largest is.

In swift, use while to execute a piece of code based on conditions until a change in the condition occurs. The condition of the loop can be placed at the end, which ensures that the loop is executed at least once.

var n = 2

While n < 100 {

n = n * 2

}

N

var m = 2

do {

m = m * 2

} While M < 100

M

In the loop, you can use the. To specify the range of an index (used in initialization, conditions, and increments) the two loops of the code below are the same effect:

var firstforloop = 0

For I in 0..3 {

Firstforloop + = i

}

Firstforloop

var secondforloop = 0

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

Secondforloop + = 1

}

Secondforloop

Use.. Determines the range, ignoring the previous value (that is, the initial value of the range), if you use ... To determine a range, include two values (initial and termination values).

Functions and Closures

/* Function and Composition */

In Swift, you use Func to declare a function, and when you call a function, you simply follow () the name of the function and add the parameter list within (). Use the Arrows (-) to separate the parameter names from the return value type of the function.

Func greet (name:string, day:string), string {///define function greet, parameter is string type name and day, return value is string

Return "Hello \ (name), today is \ (day)."

}

Greet ("Bob", "Tuesday")//Call greet function

  Experiment//Exercises

Remove the day parameter. Add a parameter to include today's lunch special in the greeting.    //delete Day This parameter, add a parameter (containing today's lunch) to the location specified in the Greet function

Multiple values can be returned from a function by combining:

Func getgasprices () (double, double, double) {

Return (3.59, 3.69, 3.79)

}

Getgasprices ()

Functions can also receive multiple parameters in the form of arrays:

Func sumof (Numbers:int ...), Int {/** definition function sumof (), parameter is numbers array */

var sum = 0/** defines the variable sum and assigns a value of 0*/

For number in numbers {/**for loop, traversing numbers array */

Sum + = number/** summation */

}

Return sum/** returns sum*/

}

Sumof ()/** call Function Sumof (), parameter not passed */

Sumof (42, 597, 12)/** call function Sumof (), pass three parameters */

  Experiment//Exercises

  Write A function that calculates the average of its arguments. Write a function that calculates the average of its parameters

Functions can be nested, nested in the inner layer of the function, you can access its outer function declaration of variables, in a complex or lengthy function, you can use nested functions to organize the schema.

Func Returnfifteen (), Int {/** definition function returnfifteen () */

var y = 10/** define variable y, assign value 10*/

Func Add () {/** definition function add () */

Y + = 5

}

Add ()/** call function Add () */

Return y/** returns the Y value */

}

Returnfifteen ()/** call function Returnfifteen () */

In Swift, a function is a basic data type, which means that a function can use another function as its return value.

Func makeincrementer () (int-int) {/** definition function makeincrementer, parameter null, return value is (int->int) */

Func AddOne (number:int), Int {/** definition function addone (), parameter is number, return value type is int*/

Return 1 + number

}

Return AddOne/** the function AddOne as the return value, returns */

}

var increment = Makeincrementer ()

Increment (7)

In Swift, a function can also receive another function as its argument.

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

}

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

Hasanymatches (Numbers, Lessthanten)

/********** Follow-up updates, please pay attention to *********/

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.