Swift and Java comparisons in functions (method/methods)

Source: Internet
Author: User
Tags variadic

1. A function is a separate block of code that is used to accomplish a specific task. The use of functions in Swift is more flexible than in Java, and in swift, functions can be treated as arguments to other functions, or functions can be returned from other functions. The definition of a function can be written in other function definitions, which allows for functional encapsulation within the scope of the nested function. The use of Swift and Java functions is similar in terms of the function's parameter value type and the return value type.

2. Declaration and invocation of functions

Swift:

Func Sayhelloagain (personname:string), String {    return""  "! " }print (Sayhelloagain ("Anna"))//  prints " Hello again, anna! "

function func as a prefix. When you specify a function return type, it is represented by the return arrow -> (a hyphen followed by a right angle bracket) followed by the name of the return type.

Java:

 Public string SayHello (String personname) {        return "Hello," +personname;    } System.out.println (SayHello ("Morden"));

3. function parameter and return value (functions Parameters and return values)

3.1 Multiple input parameters (multiple input Parameters)

Swift:

Func halfopenrangelength (Start:int, End:int),int{            return end- start        }

Java:

 Public int halfopenrangelength (intint  end) {        return end- start;    }

3.2 No parameter function (Functions without Parameters)

Swift:

Func SayHelloWorld (),string{            return "Hello World"        }

Java:

 Public String SayHelloWorld () {        return "Hello World";    }

3.3 No return value function (Functions without return values)

Swift:

func Saygoodbye (personname:string) {            print ("GoodBye, \ (personname)")        }

Java:

 Public void Saygoodbye (String personname) {        System.out.println ("Goodbye," +personname);    }

Note: Swift is much more flexible than Java syntax in terms of return values, see the following code

Func Printandcount (stringtoprint:string), Int {    print (stringtoprint)    return  Stringtoprint.characters.count}func printwithoutcounting (stringtoprint:string) {    PrintAndCount (stringToPrint )}printandcount ("Hello, World")//  prints "Hello, World" and returns a value of Printwithoutcounting ("Hello, World")//  prints ' Hello, world ' but does not return a value

The first function printAndCount , which outputs a string and returns Int the number of characters of the type. The second function printWithoutCounting calls the first function, but ignores its return value.

3.4 Multiple return value functions (Functions with multiple return values)

Func count (string:string),(Vowels:int, Consonants:int, others:int) {var vowels= 0, consonants = 0, others = 0 forcharacter in String.characters {SwitchString (character). 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":                    ++consonantsdefault:                    ++others}} return(vowels, consonants, others)}

In this example, the count function is used to calculate the number of vowels, consonants, and other letters in a string (based on the American English standard).

Let total = count ("Some arbitrary string!" ) print ("\ (total.vowels) vowels and \ (total.consonants) consonants")//  Prints "6 Vowels and consonants "

4. External parameter name (External Parameter Names)

If you want the user of a function to provide a parameter name when calling a function, you need to define one for each parameter except for the local parameter name 外部参数名 . The external parameter name is written before the local parameter name, separated by a space. The external parameter name function is formatted as follows:

Func someFunction (externalparameternamelocalparameternameInt) {    // function body goes here, and can use Localparametername     // To refer to the argument valuefor that parameter}

The SWIFT code is as follows:

Func Join (String s1:string, toString s2:string, Withjoiner joiner:string),string{        return s1 + Joiner + s2    }
= Join (string: "Hello", toString: "World", Withjoiner: ",") print (temp)

Default Parameter values. You can define each parameter in the body of the function 默认值 . When the default value is defined, this parameter can be ignored when calling this function. The code is as follows:

Func Join (String s1:string, toString s2:string, Withjoiner joiner:string = ""), string {    return< /c9> S1 + joiner + s2}

Like the first version of a join function, if joiner assigned, the function uses this string value to concatenate two strings:

Join (string: "Hello", toString: "World", Withjoiner: "-")//  returns "Hello-world"

When this function is called, if joiner the value is not specified, the function uses the default value (""):

Join (string: "Hello", toString: "World")//  returns "Hello World"

5. Variable parameters (Variadic Parameters)

One 可变参数(variadic parameter) can accept one or more values. When a function is called, you can use a mutable parameter to pass in an indeterminate number of input parameters. Variable parameters are defined by the way they are added after the variable type name (...) . The value passed in the variable parameter is treated as an array of this type in the body of the function. The code is as follows:

func Arithmeticmean (numbers:double ...) {            = 0             for item in numbers{                + = Item            }            print ("Total are \ (total)")        }arithmeticmean (1 , 2, 3, 4, 5)//  returns 3.0, which is the arithmetic meanof these five numbers arithmetic Mean (3, 8, +)//  returns 10.0, which is the arithmetic Mean of these three numbers

Note: A function can have at most one variable parameter, and it must be the last one in the parameter table. This is done to avoid ambiguity in function calls. If the function has one or more parameters with default values, and there is a mutable parameter, then the variable parameter is placed at the end of the parameter table.

6.Constant parameters and variable parameters (Constant and Variable Parameters)

function parameters are constants by default. Attempting to change the value of a parameter in the function body causes a compilation error . This means that you cannot change the value of a parameter by mistake. Sometimes, however, it is useful to have a copy of the variable value of the passed parameter in the function. You can avoid defining new variables in the function by specifying one or more arguments as variable arguments. The variable parameter is not a constant, and you can use it as a new modifiable copy in the function. Define variable parameters by adding a keyword before the parameter name var :

Func AlignRight (Var string:string, Count:int, Pad:character)string{let Amounttopad= Count-String.characters.countifAmounttopad < 1 {                returnstring} let Padstring=String (PAD) for_ in 1... amounttopad {String= Padstring +string}returnstring}let originalstring= "Hello"Let paddedstring= AlignRight (originalstring, 10, "-")//paddedstring is equal to "-----Hello"//originalstring is still equal to "hello"

Note: Modifications to variable parameters disappear after the function call ends and are not visible outside the function body. Variable parameters exist only in the life cycle of a function call.

7. Input and output parameters (In-out Parameters)

Variable parameters, can only be changed in the function body. If you want a function that modifies the value of a parameter and wants it to persist after the function call ends, define the parameter as an input-output parameter (In-out Parameters). When defining an input/output parameter, add inout the keyword before the parameter definition. An input-output parameter has the value of the passed-in function, which is modified by the function, and then the outgoing function replaces the original value. You can only use variables as input and output parameters. You cannot pass in constants or literal literals (literal value), because these quantities cannot be modified. When a parameter is passed in as an input and output parameter, it needs & to be added before the parameter , indicating that the value can be modified by the function. Note: input and output parameters cannot have default values, and mutable parameters cannot be inout marked. If you inout mark a parameter, the parameter cannot be flagged by the var person let .

func swaptwoints (inout a:int, inout b:int) {    = a    = b    = Temporarya}

We can call it with a Int variable of two types swapTwoInts . It is important to note that the someInt anotherInt prefix is added before the function is passed in, and the code is swapTwoInts & as follows:

var someint = 3= 107swaptwoints (&someint, &anotherint) print ("Someint is now \ (Someint), and Anotherint is now \ (anotherint) ")//  prints" Someint are now 107, and Anotherint I s now 3 "

From the above example, we can see that someInt anotherInt the original values are modified in the swapTwoInts function, although they are defined outside the function body. Note: the input and output parameters are not the same as the return values. The above swapTwoInts function does not define any return value, but still modifies the someInt anotherInt value of and. The input and output parameters are another way for the function to have an effect on the outside of the function body.

8. Function Types

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

8.1 Declare the function type with the following code:

Func addtwoints (A:int, b:int), int    {return A +- int {    ret Urn A * B}

8.2 Using the function type (using the Types), the code is as follows:

var mathfunction: (int, int), int = Addtwointsprint ("Result: \ (Mathfunction (2, 3))")// c3> prints "Result:5"mathfunction = multiplytwointsprint ("Result: \ (Mathfunction (2, 3)")   Prints "Result:6"

8.3 function type as parameter type (function Types as Parameter Types): You can use (Int, Int) -> Int such a function type as the parameter type of another function. This allows you to pass a part of the function implementation to the caller of the function. The code is as follows:

Func Printmathresult (mathfunction: (int, int) , int, a:int, b:int) {    print ("Result: \ (Mathfunction (A, B )) "3, 5)//  prints" Result:8 "

8.4 function type as return type (function type as return Types)

We can use the function type as the return type of another function. What needs to be done is to -> write a complete function type after returning the arrow (). In this example, two simple functions are defined, respectively, stepForward and stepBackward . stepForwardThe function returns a value that is greater than the input value. stepBackwardThe function returns a value that is one smaller than the input value. The types of the two functions are (Int) -> Int : The code is as follows:

Func Stepforward (input:int), int {    return input + 1, int {      return input-1}

chooseStepFunctionReturns a function or function based on a Boolean value backwards stepForward : The code is stepBackward as follows:

Func choosestepfunction (Backwards:bool)-(int)- int {    return backwards?  Stepbackward:stepforward}

Now you can use it chooseStepFunction to get a function, regardless of the direction:

var currentvalue = 3= choosestepfunction (CurrentValue > 0)//  Movenearertozero now Refers to the Stepbackward () function

In this example, it is calculated from the currentValue gradual approach to 0 whether it is necessary to go to a positive number or to a negative number. currentValuethe initial value is 3 , which means that it currentValue > 0 is true ( true ), which will make the chooseStepFunction return stepBackward function. A reference to the returned function is saved in the moveNearerToZero constant.

8.5 Nested functions (Nested Functions)

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 function chooseStepFunction :

Func choosestepfunction (Backwards:bool), (INT)Int {func stepforward (input:int)-Int {returnInput + 1} func Stepbackward (input:int)-Int {returnInput-1 }        returnBackwards?Stepforward:stepbackward} @IBAction func Test (sender:anyobject) {var currentvalue=-4Let Movenearertozero= choosestepfunction (CurrentValue < 0)        //Movenearertozero now refers to the nested Stepforward () function         whileCurrentValue! = 0{print ("\ (CurrentValue) ... ") CurrentValue=Movenearertozero (CurrentValue)}}
// -4...// -3...// -2...// -1...

Swift and Java comparisons in functions (method/methods)

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.