Basic syntax in Swift (II): basic syntax in swift
1. Functions in Swift
/// Function Definition //-Parameters: //-x: Shape Parameter //-y: Shape Parameter //-Returns: return Value func sum (x: Int, y: Int)-> Int {return x + y}
Print (sum (x: 10, y: 20 ))
/* If an external parameter is added to the front of the parameter, the external parameter does not affect the details of the function. External parameters make the external call more intuitive. If '_' is used '_', when a function is called externally, the parameter name "_" is ignored to ignore any uninteresting content */func sum1 (num1 x: Int, num2 y: Int) -> Int {return x + y ;}
Print (sum1 (num1: 10, num2: 20 ))
func sum2(_ x: Int, _ y:Int) -> Int { return x + y; } print(sum3())
Set the default Function
// Default value: func sum3 (x: Int = 1, y: Int = 2)-> Int {return x + y}
Flexible here
Print (sum3 (x: 10, y: 20 ))
Print (sum3 (x: 10 ))
Print (sum3 (y: 20 ))
Functions without return values
Func demo1 () {print ("Haha")} func demo2 ()-> () {print ("Haha")} func demo3 () -> Void {print (" ")}
Demo1 ()
Demo2 ()
Demo3 ()
2. Closure
// 1. closure, the simplest closure // n. If there is no parameter and no return value, you can omit the link in. // option + click let b1 = {print ("hello ")} b1 ()
// In the closure with parameters // In the closure, the parameter, the code for returned value implementation is written in {}. // you need to use the keyword "in" to separate the definition and implementation. // {form parameter list-> return value type in // implementation code} let b2 = {(x: int)-> () in print (x)} b2 (100)
// Closure with parameters that return values let b3 = {(x: Int)-> Int in return x + 1} print (b3 (10 ))
Note that,
// If the last parameter of a function is a closure function parameter, it can be terminated in advance. The last parameter uses the code of the closure wrapped in {}.
3. swift's solution to circular references
1. Solution Based on OC
// The chance for the weak referenced object to execute nil again: weak var weakSelf = self loadData {(result) in print (result, weakSelf )}}
// The functions of [weak self] and _ weak typeof (self) are similar-> if an object is recycled, the memory address will automatically point to nil. it is safer to use func methodInSwift1 () {loadData {[weak self] (result) in print (result, self )}}
// [Unowned self] and _ unsafe _ retained act similarly-> if an object is recycled, the memory address does not automatically point to nil, causing the wild pointer to access func methodInSwift2 () {loadData {[unowned self] (result) in print (result, self )}}