Definition of a function
1. Basic notation of functions
Func function name (formal parameter list), return value type
Example: Func sum (X:int, y:int), int{
Return X+y
}
Print (Sun (x:10,y:50))
2. The use of external parameters is to add a name before the parameter, the external parameters will not affect the internal details of the function, external parameters will make the external call look more intuitive
Example: Func sum (num1 x:int, num2 y:int), int{
Return X+y
}
Print (sum (num1:30,num2:40))
The use of "_" can be used to replace the non-care of the display, and the usual for the "I" in the loop if no use of the case to, you can use "_" instead of
Func Sun (_ X:int, _ Y:int), int{
Return X+y
}
Print (sum (30,40))
3. Default value: By setting the default value for the parameter, when called, you can combine the parameters arbitrarily, if not specified, use the default value. However, in OC it is not possible to define multiple functions
Example: Func sum (x:int=1,y:int=2), int{
Return X+y
}
Print (sum ())
Print (sum (x:10,y:10))
Print (sum (x:10))
...
4. Absence of return value: mainly used in closures
Example: func demo () {}
Func demo1 (), () {}
Func Demo2 ()->void {}
Closed Package
1. Closure definition: block similar to OC, but more extensive than block application
Block is an anonymous function in OC
Functions in Swift are special closures
1. Pre-prepared code
2. Execute when needed
3. Can be passed as parameters
Example of a function assignment that cannot be implemented in 1:OC
Func sum (x:int=1,y:int=2), int{
Return X+y
}
Let f = Sum
Print (f (x:20,y:40))
Example 2: A simple closure
function B1 without parameters and return values (in which case parameters and return values can be omitted, including "in")
Let B1 = {
Print ("Hello word")
}
Execute closures
B1 ()
Example 3: Closure with parameters
Closure, parameter, return value, implementation code is written in {}
{parameter list, return value in implementation code}
Need to use "in" to split the definition and implementation
Let B2 = {
(X:int), () in
Print (x)
}
B2 (100)
Example 4: Closures with parameters and return values
Let B3 = {
(x:int), int in
Return x+200
}
Print (B3 (1111))
How to use GCD in 2.swift
1.GCD: Add task to queue, specify function to perform task
2. Translation: Queue scheduling task (block/closure) to execute synchronously/asynchronously
Example: Func LoadData (), () {
Dispatchqueue.global (). async{
Print ("time-consuming Operation \ (Thread.current ())")
DispatchQueue.main.async (execute:{
Print ("Main thread update UI \ (Thread.current ())")
})
}
}
3. Perform the task asynchronously, get the result, and pass the block/closure callback. Closures are fully consistent with block scenarios
Format definition Features
1. return value with parameters
2. LoadData (Completion: (Result: [string])-() () () (Completion: (Result: [string])--()) parameter, followed by the return value 。
3.completion: (Result: [string])--(Result: [string]) is the return value after the argument
Example: Func loaddata (Completion: (Result: [String]), ()) {
Dispatchqueue.global (). async{
Print ("time-consuming Operation \ (Thread.current ())")
Thread.Sleep (fortimeinterval:1.0)
Let JSON = ["headline", "Gossip", "weather"]
DispatchQueue.main.async (execute:{
Print ("Main thread update UI \ (Thread.current ())")
Execute closures
Completion (Result:json)
})
}
}
Call
loaddata{
(Result) in
Print ("Get success \ (Result)")
}
4. Trailing closure: If the last parameter of the function is a closure, the function parameter can be terminated prematurely, and the last parameter is used to package the closure code directly with {} (example 3)
The original invocation method (results written by the function itself)
LoadData (
completion:{(Result), () in
Print ("Get success \ (Result)")
}
)
Nested trailing closures are (systems) that do not automatically prompt for trailing closures, for example in 2. Of course, you can manually delete the extra to write the trailing closure style again, easy to read
Func LoadData (), () {
Dispatchqueue.global (). async{
Print ("time-consuming Operation \ (Thread.current ())")
dispatchqueue.main.async{
Print ("Main thread update UI \ (Thread.current ())")
}
}
}
5. You can use {} to differentiate scopes in OC. However, in swift it is not possible to encounter {} in Swift that may be recognized as a closure
Cyclic applications in 6.swift:
1. How to use OC
weak var weakself = self
loaddata{
Print (weakself?. View
}
Detail 1: To use the Var modifier you cannot use let. Because weak may be modified at run time. Once a weak object is disposed, it is automatically set to nil, and all cannot be
Detail 2:? (optional unpacking) is usually used to send messages simply, no calculations! (forcibly unpacking) the forced unpacking must have a value that, if not, would cause a crash, typically used to calculate
2.Swift Recommended method
loaddata{
[Weak self] in
Print (self?. View
}
[Weak self] means that all self in the closure is quoted, note unpacking
A special method for 3.Swift (not recommended)
loaddata{
[unowned Self] in
Print (self?. View
}
[unowned self] means that all of the closures are assign and are not strongly referenced. But the object release pointer address does not change, if the object is released, continue to call will cause the problem of wild pointers
7. [Weak self] is a weak reference for the closure of the whole, and is automatically set to nil, equivalent to the __weak in OC, if it is freed
[unowned Self] is the assign of self in the closure, if self is freed, the pointer address remains the same, and a wild pointer error occurs, equivalent to __unsafe_unretained in OC
Demo:https://github.com/fushengit/learn-swift
Swift Learning (2 function closures)