Swift Study Notes 1: swift Study Notes
When reading Developing IOS 8 Apps with swift, you can see some useful points and record them:
1. Pass functions as parameters. For example:
Write a function that sums two numbers:PerformOperation (multiply)
func performOperation(operation:(Double,Double) -> Double) { if operandStack.count >= 2 { dispalayValue = operation(operandStack.removeLast(),operandStack.removeLast()) enter() } } func multiply(op1: Double, op2: Double) -> Double { return op1 * op2 }The above is a cool implementation, using the closure method:
Improvement:
performOperation ({ (op1: Double, op2: Double) -> Double in return op1 * op2 }) func performOperation(operation:(Double,Double) -> Double) { if operandStack.count >= 2 { dispalayValue = operation(operandStack.removeLast(),operandStack.removeLast()) enter() } }The compiler will deduce the type based on the context. Therefore, the above performOperaion can be simplified:
performOperation ({ (op1, op2) in return op1 * op2 })The types of op1 and op2 can be inferred. Of course, the return type can also be inferred. Therefore, the return type can be omitted, and even the return type can be omitted.
Since the compiler does not force you to write the form parameter, op1 and op2 can also be omitted here, with $0, $1, $2 ,...... represents the first, second, and third parameters,
Therefore, the above can be simplified:
performOperation ({ op1 * op2 })The swift compiler is really TMD only, haha!
Wait, it's not over,
Simplified:
performOperation () { op1 * op2 }</span>There is a condition, that is, when op1 * op2 is passed as the last parameter, you can do this by moving the function parameter out of the brackets, as shown above. For others, if there is another parameter, it can be placed in brackets () as before; if there is only one parameter, the brackets can also be removed directly, as shown below:
performOperation { op1 * op2 }Now, the process is simplified.
2. swift supports polymorphism. What an amazing!
For example, if you require a square root of a number, you still want to use the original function called moperation. However, this function requires a form parameter that contains two Double types, to evaluate the square root, you only need to input a parameter. Then, let's transform this function. Write a function named performOperation with the same name, and define it as only one form parameter.
Note: swift supports multiple functions with the same name in a class at the same time, and the form parameters are different, meaning polymorphism ~
Then, add the performOperation function as follows:
func performOperation(operation: Double -> Double) { if operandStack.count >= 1 { dispalayValue = operation(operandStack.removeLast()) enter() } }Now we can call this method to calculate the square root of a value.
performOperation { sqrt($0) }
For More information, see the More Xcode and Swift and MVC sections of Developing IOS 8 Apps with Swift.