Swift Chinese tutorial (iv) -- functions and closures

Source: Internet
Author: User

Function

Swift uses the func keyword to declare a function. The function is called through the parameter list in the function name and parentheses. Use-> to distinguish between parameter names and return value types:

1 func greet(name: String, day: String) -> String {2     return "Hello \(name), today is \(day)."3 }4 greet("Bob", "Tuesday")

Exercise:

Remove day parameter, add a parameter, for example, today's lunch special dish ~

1 func greet (name: String, day: String)-> String {2 3 return "Hello \ (name), today is \ (day ). "// Chapter 2 describes how to use \ () to embed variable 4 5} 6 7 greet ('job', 'bodhi yuzhai ')

 

 

The function uses tuple to return multiple values:

1 func getGasPrices() -> (Double, Double, Double) {2     return (3.59, 3.69, 3.79)3 }4 getGasPrices()

 

The function can also receive variable parameter numbers and collect these parameters in the array:

1 func sumOf(numbers: Int...) -> Int {2     var sum = 03     for number in numbers {4         sum += number5     }6     return sum7 }8 sumOf()9 sumOf(42, 597, 12)

Exercise:

Compile a function and obtain the average value of its parameters.

 

Functions can be nested. nested functions can access variables declared by external functions. Using function nesting can facilitate the organization of long or complex functions:

1 func returnFifteen() -> Int {2     var y = 103     func add() {4         y += 55     }6     add()7     return y8 }9 returnFifteen()

 

In Swift, the function is of the first type, which means that a function can use another function as its return value:

1 func makeIncrementer() -> (Int -> Int) {2     func addOne(number: Int) -> Int {3         return 1 + number4     }5     return addOne6 }7 var increment = makeIncrementer()8 increment(7)

 

The function can also receive other functions as its parameters:

 1 func hasAnyMatches(list: Int[], condition: Int -> Bool) -> Bool { 2     for item in list { 3         if condition(item) { 4             return true 5         } 6     } 7     return false 8 } 9 func lessThanTen(number: Int) -> Bool {10     return number < 1011 }12 var numbers = [20, 19, 7, 12]13 hasAnyMatches(numbers, lessThanTen)

  

  Closure

  

A function is actually a special case of closure. You can write an anonymous closure wrapped with curly braces {} and use in to distinguish the return type of parameters from the subject:

1 numbers.map({2     (number: Int) -> Int in3     let result = 3 * number4     return result5     })

Exercise:

Override this closure to return 0 for all odd numbers.

 

Closure has a variety of simple writing methods. When the type of the returned value is known, for example, the delegate callback, You can omit its parameter type, select its return value class, or skip both, the closure of a single-row statement can directly and implicitly return the value of this statement:

1 numbers.map({ number in 3 * number })

 

You can reference a parameter by number rather than name, which is very useful for very short closures. A closure uses parentheses to pass its last parameter to the function for immediate effect:

1 sort([1, 5, 3, 12, 2]) { $0 > $1 }

 

 

Thank you, Swifter-QQ group: 362232993 ~

Github address: https://github.com/Joejo/Swift-lesson-for-chinese

 

 

 

 

 

 

 

 

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.