Functions and closures functions and closures)
Use of functions
There is a significant difference between Function Definition and OC in swift. Use func to define the function, define the number and type of struct in brackets, and use-> to define the type of return value.
func greet(name: String, day: String) -> String { return "Hello \(name), today is \(day)."}greet("Bob", "Tuesday")
Use a single tuple () to return multiple return values
func getGasPrices() -> (Double, Double, Double) { return (3.59, 3.69, 3.79)}getGasPrices()
The function can also have a variable number of shards (in this case, it is better to input an array). Note that there are three points...
func sumOf(numbers: Int...) -> Int { var sum = 0 for number in numbers { sum += number } return sum}sumOf()sumOf(42, 597, 12)
Functions can also be nested. nested functions can be used to explain external function variables.
func returnFifteen() -> Int { var y = 10 func add() { y += 5 } add() return y}returnFifteen()
New Feature: swift defines a function as a type, that is, it can define a function variable. The return value of a function can be a function.
func makeIncrementer() -> (Int -> Int) { func addOne(number: Int) -> Int { return 1 + number } return addOne}var increment = makeIncrementer()increment(7)
A function can use another function as its limit number.
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)
Use of closures Closure
A function is actually a closure. You can define a closure without a name. You only need to include the closure with braces, use in to divide variables and return values (in fact, similar to block in OC)
numbers.map({ (number: Int) -> Int in let result = 3 * number return result })
You can omit the number of records and return values to make the closure above a more simple introduction. Just one closure of a statement directly returns the running result of this statement.
numbers.map({ number in 3 * number })
You can also write a closure behind the brackets.
sort([1, 5, 3, 12, 2]) { $0 > $1 }
Next, let's talk about objects and classes.