Swift-Function (Functions) Summary-comparison vs C # similarities and differences

Source: Internet
Author: User
Tags mathematical functions


1.0 definition and invocation of functions (defining and calling Functions)


Accustomed to C # syntax, see the following to define the input parameters are very awkward, func a bit JavaScript feel, still a habit. function calls are no different from other languages


// function with input parameters and return value
// The input parameter is name, and the data type is String
// Return value String
func SayHello (name: String)-> String {
     return "Hello," + name;
}
//call function
SayHello ("_ luo")
2.0 function parameter and return value (functions Parameters and return values)
// 2.1 Multiple Input Parameters
func HalfOpenRangeLength (start: Int, end: Int)-> Int {
    return end-start;
}
// 2.2 Functions Without Parameters
func SayHelloWorld ()-> String {
return "Hello World";
}

// 2.3 Functions Without Return Values
func SayGoodbye (name: String) {
    println ("Goodbye, \ (name)");
}

// 2.4 Functions with Multiple Return Values
// You can use tuple type to return multiple values from a function as a composite value.
// Count the number of vowels, consonants and other letters in a string
func Count (str: String)-> (vowels: Int, consonants: Int, others: Int) {
    var vowels = 0, consonants = 0, others = 0;
    for item in str {
        switch String (item) .lowercaseString {
        case "a", "e", "i", "o", "u": vowels ++;
        case "b", "c", "d", "f", "g", "h", "j", "k", "l", "m",
        "n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z": consonants ++;
        default: others ++;}
    }
    return (vowels, consonants, others);
}
3.0 function parameter name (functions Parameter Names)


The parameter name in the function above is only used in the body of the function and cannot be used when this function is called, and the parameter name for this type is [ local parameter name ].



In contrast to C #, Swift has an external parameter name.



The external parameter name is used to indicate what the individual arguments are used for when the function is called.



(Personal feel is really too impersonal, in order to know the meaning of this parameter also need to get an external parameter name.) C # is better at VS, as long as the comments are written, the call will show the purpose of each parameter, immediately feel the power of vs.


// 3.1 External Parameter Names
// External parameter names are written before local parameter names, separated by spaces
// If you provide an external parameter name, the function must use the external parameter name when it is called.
// ---- No wording for external parameter names ?? -----
func Join (str1: String, str2: String, joinner: String)-> String {
    return str1 + joinner + str2;
}
// When you call this function, the purpose of these three strings is unclear
Join ("Hello", "World", ",")

// To make the use of these strings more obvious, we add external parameter names for the Join function
func Join (string str1: String, toString str2: String, withJoiner joinner: String)-> String {
    return str1 + joinner + str2;
}
// Now you can use these external parameter names to call the function in a clear way:
Join (string: "Hello", toString: "World", withJoiner: ",");

// 3.2 Shorthand External Parameter Names
// If the external parameter name you need to provide is a local parameter name, then just write the parameter name once and prefix it with ##
func ContainsCharacter (#str: String, # char: Character)-> Bool {
    for item in str {
        if (item == char) {
            return true;
        }
    }
    return false;
}

ContainsCharacter (str: "klsdkfjoiwenklaskdf", char: "a")

// 3.3 Default Parameter Values
// 3.4 External Names for Default Value Parameters (External Names for Parameters with Default Values)
// In most cases, it is useful to give an external parameter name to a parameter with a default value. This ensures that when the function is called, the intent of the arguments is obvious.
// To make the definition of external parameter names more robust, Swift will automatically provide external names when you don't provide external parameter names for parameters with default values. At this point, the external parameter name is the same as the local name, just like you have written # before the local parameter name.
func Join (str1: String, str2: String, joinner: String = "")-> String {
    return str1 + joinner + str2;
}
Join ("Hello", "World", joinner: "-")

// 3.5 Variadic Parameters
// Define the variable parameter by adding the ...
// Calculate the arithmetic mean of a set of numbers of any length
func AritheticMean (numbers: Double ...)-> Double {
    var total: Double = 0;
    for number in numbers {
        total + = number;
        
    }
    return total / Double (numbers.count);
}
AritheticMean (1,2,2,1,23,22,12)
// Note: A function can have at most one variable parameter, and it must be the last one in the parameter list

// 3.6 Constant and Variable Parameters
// Function parameters are constant by default. Attempting to change parameter values in this function body will cause mutation errors. You can define variable parameters by adding the keyword var before the parameter name.
// align text to the right
func TextAlignRight (var str: String, totallength: Int, pad: Character)-> String {
   
    let amountToPad = totallength-count (str);
    if (amountToPad <= 0) {
        return str;
    }
    for _ in 1 ... amountToPad {
        str = String (pad) + str;
    }
    return str;
}

TextAlignRight ("loding", 10, "-") --------- // "---- loding"
TextAlignRight ("Error", 10, "-") ---------- // "----- Error"
4.0 function type (functions Types)


Each function has a specific type of function, which consists of the parameter type and the return type of the function.



For example:


func addTwoInts(a: Int, b: Int) -> Int {
    return a + b
}
func multiplyTwoInts(a: Int, b: Int) -> Int {
    return a * b
}


In this example, two simple mathematical functions are defined:addTwoIntsandmultiplyTwoInts. Both of these functions pass in twoInttypes, returning an appropriateIntvalue.



The type of these two functions is(Int, Int) -> Int, can be read as "This function type, it has two typesIntof parameters and returns aInttype of value." ”。



Here is another example of a function that has no parameters and no return value:


func printHelloWorld() {
    println("hello, world")
}


The type of this function is:() -> (), or "function without parameters and returnVoidtype". Functions that do not specify a return type are always returnedVoid. In Swift,Voidit is the same as an empty tuple.



The next step is to look at the use of the function type, and you can find a delegate similar to C #


// 4.1 using function types
// In Swift, using function types is just like using other types. For example, you can define a constant or variable of type function and assign a function to it:
var mathFunction: (Int, Int)-> Int = addTwoInts
println ("Result: \ (mathFunction (2, 3))")
// prints "Result: 5"

// Different functions with the same matching type can be assigned to the same variable, just like non-function type variables:
mathFunction = multiplyTwoInts
println ("Result: \ (mathFunction (2, 3))")
// prints "Result: 6"

// Like other types, when assigning a function to a constant or variable, you can let Swift infer its function type:
let anotherMathFunction = addTwoInts
// anotherMathFunction is inferred to be of type (Int, Int)-> Int

// 4.2 Function Types as Parameter Types
// You can use a function type like (Int, Int)-> Int as the parameter type of another function. This way you can delegate part of the implementation of the function to the caller of the function.
// Here is another example. Just like the above function, it also outputs the result of some mathematical operation:
func printMathResult (mathFunction: (Int, Int)-> Int, a: Int, b: Int) {
    println ("Result: \ (mathFunction (a, b))")
}
printMathResult (addTwoInts, 3, 5)
// prints "Result: 8"

// 4.3 Function Type as Return Types
// You can use a function type as the return type of another function. What you need to do is write a complete function type after the return arrow (->).
// The following example defines two simple functions, stepForward and stepBackward. The stepForward function returns a value that is one greater than the input value. The stepBackward function returns a value that is one less than the input value. Both functions are of type (Int)-> Int:
func stepForward (input: Int)-> Int {
    return input + 1
}
func stepBackward (input: Int)-> Int {
    return input-1
}
// The following function is called chooseStepFunction, and its return type is (Int)-> Int. chooseStepFunction returns a stepForward function or a stepBackward function based on the boolean backwards:
func chooseStepFunction (backwards: Bool)-> (Int)-> Int {
    return backwards? stepBackward: stepForward
}
// You can now use chooseStepFunction to get a function, no matter which direction:
var currentValue = 3
let moveNearerToZero = chooseStepFunction (currentValue> 0)
// moveNearerToZero now refers to the stepBackward () function

// In the above example, it is calculated whether it is necessary to go to a positive or negative number from the currentValue approaching 0. The initial value of currentValue is 3, which means that currentValue> 0 is true, which will cause chooseStepFunction to return the stepBackward function. A reference to the returned function is stored in the moveNearerToZero constant.

// Now moveNearerToZero points to the correct function, which can be used to count to 0:
println ("Counting to zero:")
// Counting to zero:
while currentValue! = 0 {
    println ("\ (currentValue) ...")
    currentValue = moveNearerToZero (currentValue)
}
println ("zero!")
// 3 ...
// 2...
// 1...
// zero!
5.0 nested functions (Nested Functions)


In the example above, all the functions you see are called global functions, which are defined in the global domain. You can also define functions in other function bodies, called nested functions (nested functions).



By default, nested functions are invisible to the outside world, but can be called by their enclosing function (enclosing functions). A closed function can also return one of its nested functions so that the function can be used in other domains.



You can override the function in a way that returns a nested functionchooseStepFunction:


func chooseStepFunction (backwards: Bool)-> (Int)-> Int {
     func stepForward (input: Int)-> Int {return input + 1}
     func stepBackward (input: Int)-> Int {return input-1}
     return backwards? stepBackward: stepForward
}
var currentValue = -4
let moveNearerToZero = chooseStepFunction (currentValue> 0)
// moveNearerToZero now refers to the nested stepForward () function
while currentValue! = 0 {
     println ("\ (currentValue) ...")
     currentValue = moveNearerToZero (currentValue)
}
println ("zero!")
result:
// -4 ...
// -3 ...
// -2...
// -1...
// zero! 


Swift-Function (Functions) Summary-comparison vs C # similarities and differences


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.