Swift2.0 The return value and function type of the function of the language tutorial

Source: Internet
Author: User
Tags types of functions

Swift2.0 The return value of the function in the language tutorial and the function type Swift2.0 the return value of the function

Functions can be divided into non-return-valued functions and return-valued functions, depending on whether they have return values. The two types of functions are explained below.

A function with a return value in the Swift2.0

The developer wants to return the value of a data type in the function, and must set a return data type for the function when the function declaration is defined and return using the return statement. Where the general representation of the return statement is as follows:

    • return expression

Where an expression can be any expression that conforms to the SWIFT standard. A function declaration with a return value is defined as follows:

    • Func function name (parameter list), return value type {
    • Statement
    • return expression
    • }

Where the returned expression type must be the same as the return value type of the function.

"Example 7-13" The following code calculates the length of a range of values and returns the output. The code is as follows:

    • Import Foundation
    • Func range (Start:int,end:int)->int{
    • return End-start
    • }
    • Let A=range (0, End:10)
    • Print (a)

In code, the return value type of the specified function is int, and the return expression is End-start. The results of the operation are as follows:

    • 10

Functions with multiple return values in Swift2.0

In Swift, a function can not only return a return value, but can also return more than one, which is required to use the tuple type. Its grammatical form is as follows:

    • Func count (parameter list) -- return value 1: data type, return value 2: data type, return value 3: data type, ...) {
    • ......
    • Return ( returns a value of 1, returns a value of 2, Returns a value of 3,...)
    • }

"Example 7-14" gets the number of vowels, consonants, and other numbers in a string. The code is as follows:

  • Import Foundation
  • Func count (string:string) --(Vowels:int, Consonants:int, Others:int) {
  • var vowels = 0, consonants = 0, others = 0
  • For character in String.characters {
  • Switch String (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":
  • ++consonants
  • Default
  • ++others
  • }
  • }
  • return (vowels, consonants, others)
  • }
  • Let str= "Hello swift!"
  • Let Number=count (str)
  • Print ("\ (number.vowels) vowel \n\ (number.consonants) consonant \n\ (number.others) Other")

The results of the operation are as follows:

    • 3 Vowel
    • 7 consonants
    • 2 other

In a function with multiple return values, note the following 2 points:

1. The number of return values is the same

The number of return value types followed by is the same as the number of return values in return, or the program will have an error. The code in example 7-14 is modified as follows:

    • Func count (string:string)--(Vowels:int, Consonants:int, Others:int) {
    • var vowels = 0, consonants = 0, others = 0
    • ...
    • return (vowels, consonants)
    • }

In this code it is known that there are 3 return value types after,->, but there are 2 return values in return, and their number is different, causing the program to have the following error:

Tuple types ' (@lvalue int, @lvalue int) ' and ' (Vowels:int, Consonants:int, Others:int) ' have a different number of Elem Ents (2 vs. 3)

2. Order of Return values

The return value type followed by is the same order as the return value type in return, or the program will have an error. The code in example 7-14 is modified as follows:

    • Func count (string:string)--(Vowels:int, Consonants:int, Others:int) {
    • var vowels = 0, consonants = 0, others = 0
    • ...
    • Return (vowels,others,consonants)
    • }

The return value after,-> in this code is (Vowels:int, Consonants:int, Others:int), and the return value in return is (vowels,others,consonants) because their data type is the same integer type , so after changing their position, the program will not have an error. The operating structure is as follows:

    • 3 vowels
    • 2 consonants
    • 7 Other

No return value in Swift2.0

The function has no type of return value in addition to a return value type. In sections 7.2, 7.3, and 7.4, there is a function type that has no return value. A type that does not have a return value does not need to define a return value type, and no return statement is required. If a return statement appears, it can cause a program error. For example, the following code, its function is to output a certain number.

    • Import Foundation
    • Func Printaa (a:int) {
    • return a
    • }
    • Let num=9
    • Let Number=printaa (num)
    • Print (number)

In this function, it has no return value, but in the function it uses the Renturn statement to return the value of a, causing the program to have the following error message:

    • ' Int ' is not convertible to ' () '

function types in Swift2.0

In swift, each function is a specific type, which is called a function type. It is comprised of the parameter type and the return value type. For example, the following code is a function with a parameter type and a return value type:

    • Func Add (A:int, b:int), Int {
    • Return a + b
    • }

In this code, a mathematical function add that implements the addition operation is defined. This function takes a parameter of two int integer and, after performing the corresponding mathematical operation, returns an int integer value as the result. The type of this function is (int,int)->int, the programmer can understand that the function type has two int integer parameters and returns an int integer value. In addition to a function with a parameter list and a return value type, Swift has functions without parameters and return value types, such as the following code is a function without parameters and return values:

    • Func Printhelloworld () {
    • Print ("Hello,world")
    • }

The type of function Printhelloworld () is (), (). Because the function has no parameters, it returns void, so the type is equivalent to an empty tuple in swift, or it can be simplified to ().

Using function types in Swift2.0

As a type, programmers can use function types just like any other type. The basic syntax is as follows:

    • LET/VAR constant Name/variable name: function type = functional name
    • Or
    • LET/VAR constant Name/variable name = function name

"Example 7-15" The following will use a mathfunction variable to refer to the function Add. The code is as follows:

    • Import Foundation
    • Func Add (A:int, b:int), Int {
    • Return a + b
    • }
    • var mathfunction: (int, int), int = add
    • Print (Mathfunction (2,8))

A mathfunction variable is defined in the code and the type of the variable is set to the function type. It accepts a value of two int and returns an int integer value. Use this new variable mathfunction to refer to the function of the add function. The results of the operation are as follows:

    • 10

Because Swift has the ability to infer types automatically, it is possible to assign values directly after declaring a variable without requiring a single declaration type for the variable, so the above code that assigns a value to the variable can be rewritten as:

    • var mathfunction = add

If different functions have the same function type, assign them to the same variable. For example, in the above code, add a function:

    • Func Multiply (a:int,b:int)->int{
    • Return a*b
    • }

Since the mathfunction variable and the multiply type match, it is possible to assign the value directly and output the code as follows:

    • Mathfunction=multiply
    • Print (Mathfunction (3,8))

The code looks like this:

    • 10
    • 24

Using function types as parameter types in Swift2.0

A developer can use a function type as a parameter type for another function. For example, the following code, its function is to let the number to add or multiply, and then output. The code is as follows:

    • Import Foundation
    • Add two numbers
    • Func Add (A:int, b:int), Int {
    • Return a + b
    • }
    • Multiply two numbers
    • Func Multiply (a:int,b:int)->int{
    • Return a*b
    • }
    • Output results
    • Func Printresult (fun: (int,int)->int,a:int,b:int) {
    • Print (fun (b))
    • }
    • Printresult (Add, A:3, B:2)
    • Printresult (multiply, a:3, b:2)

Three functions are defined in this code. In the third function Printresult, there are three parameters: the first parameter is fun, the type is (Int,int)->int, the developer can pass in any function of this type, the second argument and the third argument are A and B, respectively, they are of type Int, These two values are the input values of the function. When the Printresult function is called for the first time, it passes in the Add function and 3, 52 integers. At this point, it will call the function add, 3, 5 as the input value of the function add, and output the result. Second, this call is similar, and printresult calls the multiply function. The results of the final run are as follows:

    • 5
    • 6

Use function type as return value type in Swift2.0

A function type can be used not only as a parameter, but also as a return value type. At this point, you need to write a complete function type in the following syntax:

    • Func function name (argument list), function type {
    • ...
    • }

"Example 7-16" The following code outputs a series of values by a given value, if the given value is greater than 0 the number of outputs from this number to 0, and if it is a negative number, the output is a small 1. The code is as follows:

    • Import Foundation
    • Returns a value 1 greater than the input value
    • Func Stepforward (input:int), Int {
    • return input + 1
    • }
    • Returns a value 1 smaller than the input value
    • Func Stepbackward (input:int), Int {
    • Return input-1
    • }
    • Choose which function to return
    • Func choosestepfunction (Backwards:bool) -(int)-int {
    • Return backwards? Stepbackward:stepforward
    • }
    • var currentvalue = 5
    • Let Movenearertozero = Choosestepfunction (currentvalue>0)
    • While CurrentValue! = 0 {
    • Print ("\ (CurrentValue) ... ")
    • CurrentValue = Movenearertozero (currentvalue)
    • }

3 functions are defined in this code. The return value type of the third function choosestepfunction is (Int)->int. The results of the operation are as follows:

    • 5 ...
    • 4 ...
    • 3 ...
    • 2 ...
    • 1 ...
    • Standard functions in the Swift2.0

In addition to the function can be divided into the parameters of the parameter list of non-parametric function and parameter function, but also from the definition of the angle can be divided into user-defined function and standard function two. The above examples are user-defined functions. SWIFT provides 74 standard functions that can be used directly, without the need to define them. This section explains in detail the standard functions that are commonly used.

Swift2.0 Absolute Function abs ()

The function of the ABS () function is to calculate the absolute value of a number. Its grammatical form is as follows:

    • ABS (value)

The return value of the function is a 0 or a positive number.

Example 7-17 below will use the ABS () function to get the absolute value of-10, 10, 0,-1.233, 1.233. The code is as follows:

    • Import Foundation
    • To find the absolute value of an integer
    • Let Value1=abs (-10)
    • Let Value2=abs (10)
    • Let Value3=abs (0)
    • // find the absolute value of a floating-point number
    • Let Value4=abs (-1.233)
    • Let Value5=abs (1.233)
    • Print ("value1=\ (value1)")
    • Print ("value2=\ (value2)")
    • Print ("value3=\ (VALUE3)")
    • Print ("value4=\ (value4)")
    • Print ("value5=\ (value5)")

In this code, the absolute value of a positive number is itself, the absolute value of a negative number is positive, and the absolute value of 0 is 0. The results of the operation are as follows:

    • value1=10
    • value2=10
    • Value3=0
    • value4=1.233
    • value5=1.233

Note: The parameters in ABS () must be numeric, not something other than a numeric value, such as a character, a string, and so on. The absolute value of the string "AAA" is obtained, as in the following code. The code is as follows:

    • Import Foundation
    • Let Value1=abs ("AAA")
    • Print ("value1=\ (value1)")

The program has the following error because the parameter of ABS () is a string:

    • Cannot find an overload for ' ABS ', accepts an argument list of type ' (String) '

Swift2.0 max function Max ()/min. min ()

In programming, it is often necessary to calculate the maximum or minimum values for several parameters, which can be achieved using the Max () and Min () functions in the standard functions. The following is a detailed explanation of these two functions.

1. Get the maximum value

The max () function can get the maximum value of several parameters. Its grammatical form is as follows:

    • Max (parameter 1, parameter 2, parameter 3,...)

Where the argument can be a numeric value, or it can be a string or a character.

Example 7-18 the following will use the Max () function to get the maximum values of 1.9 and 10, the maximum of 13.8, 20, 88.88, and the maximum value of the string "Hello", "Swift", and "Zone". The code is as follows:

    • Import Foundation
    • Let Maxvalue1=max (1.9,10)
    • Let Maxvalue2=max (13.8,20,88.88)
    • Let Maxvalue3=max ("Hello", "Swift", "Zone")
    • Print ("maxvalue1=\ (maxValue1)")
    • Print ("maxvalue2=\ (maxValue2)")
    • Print ("maxvalue3=\ (MAXVALUE3)")

When a string is compared, the characters in the string are compared. The first character of the 3 characters is judged by which is the big one. If the maximum character is found, the string beginning with this character is the maximum value, and if the 3 first characters are judged to be the same, then the second character is compared, and so on. The results of the operation are as follows:

    • maxvalue1=10.0
    • maxvalue2=88.88
    • Maxvalue3=zone

2. Get the minimum value

The min () function can get the minimum value of several parameters. Its grammatical form is as follows:

    • Min (parameter 1, parameter 2, parameter 3,...)

Where the parameter can also be a numeric value, a string, or a character.

Example 7-19 below uses the min () function to get the minimum value of 1.9 and 10 for the minimum value of 13.8, 20, 88.88, and the minimum value for the string "Swift", "Hello", and "IOS". The code is as follows:

    • Import Foundation
    • Let Minvalue1=min (1.9,10)
    • Let Minvalue2=min (13.8,20,88.88)
    • Let Minvalue3=min ("Swift", "Hello", "IOS")
    • Print ("minvalue1=\ (minValue1)")
    • Print ("minvalue2=\ (minValue2)")
    • Print ("minvalue3=\ (MINVALUE3)")

The results of the operation are as follows:

    • minvalue1=1.9
    • minvalue2=13.8
    • Minvalue3=hello

Note: If you use Max (), Min () as a numeric value, the comparison parameter is numeric. If it is a character or string, the parameter being compared is also a character or string. You cannot compare numeric values and strings, characters in one function at the same time. The following code compares the minimum value of 1.9, 10, and the string "Hello". The code is as follows:

    • Import Foundation
    • Let Minvalue=min (1.9,10, "Hello")
    • println ("minvalue=\ (minValue)")

In this code, because the min () function compares numeric values to strings, the program has the following error:

    • Cannot find a overload for ' min ' that accepts an argument list of type ' (Double, Int, String) '

Swift2.0 maximum function maxelement ()/Minimum function minelement ()

In a sequence, it is often necessary to get the maximum or minimum value of an element. You can now use the maxelement () and minelement () functions. The following is a detailed explanation of these two functions.

1. Maximum value of the sequence

The Maxelement () function gets the element with the largest value in a sequence. Its grammatical form is as follows:

    • Sequence. Maxelement ()

Where the sequence can be a numeric value, or it can be a range.

Under example 7-20, use the maxelement () function to get the sequence Sequence1, Sequence2, and range 1 ... The element of the maximum value in 100. The code is as follows:

    • Import Foundation
    • Let sequence1=[9,8,2,3]
    • Let sequence2=["Ad", "Ab", "Ac"]
    • Let Maxvalue1=sequence1.maxelement ()!
    • Print ("maxvalue1=\ (maxValue1)")
    • Let maxvalue2= (1...100). Maxelement ()!
    • Print ("maxvalue2=\ (maxValue2)")
    • Let Maxvalue3=sequence2.maxelement ()!
    • Print ("maxvalue3=\ (MAXVALUE3)")

The sequence sequence2 of a string is judged in the same way as the function Max (), which compares the letter size of the string in turn. The results of the operation are as follows:

    • Maxvalue1=9
    • maxvalue2=100
    • Maxvalue3=ad

2. Minimum value of the sequence

The Minelement () function can get the element with the smallest value in a sequence. Its grammatical form is as follows:

Sequence. Minelement ()

Where the sequence can be a numeric value, or it can be a range.

"Example 7-21" The following will use the Minelement () function to get the sequence Sequence1, Sequence2, and range 1 ... The element of the minimum value in 100. The code is as follows:

    • Import Foundation
    • Let sequence1=[9,8,2,3]
    • Let sequence2=["Ad", "Ab", "Ac"]
    • Let Minvalue1=sequence1.minelement ()!
    • Print ("minvalue1=\ (minValue1)")
    • Let minvalue2= (1...100). Minelement ()!
    • Print ("minvalue2=\ (minValue2)")
    • Let Minvalue3=sequence2.minelement ()!
    • Print ("minvalue3=\ (MINVALUE3)")

The results of the operation are as follows:

    • minvalue1=2
    • Minvalue2=1
    • Minvalue3=ab

SWIFT2.0 determines whether a sequence contains the specified element function contains ()

The contains () function can determine whether a sequence contains the specified element. Its grammatical form is as follows:

    • Sequence. Contains (Element)

Where the return value type of the function is a Boolean type. When True is returned, the expression sequence contains the specified element, and when False is returned, the representation is not included.

Example 7-22 The following code uses the CONTAINS () function function to determine whether the sequence languages contains element "Swift" and "Java". The code is as follows:

    • Import Foundation
    • var languages = ["Swift", "Objective-c", "C"]
    • Determine if the "Swift" string is included in the languages array
    • If languages.contains ("Swift") = = True {
    • Print ("languages contains element" Swift "in sequence)
    • }else{
    • Print ("The languages sequence does not contain element" Swift ")
    • }
    • Determine if a "Java" string is included in the languages array
    • If languages.contains ("Java") = = True {
    • Print ("languages sequence contains element" Java ")
    • }else{
    • Print ("The languages sequence contains no element" Java ")
    • }

In this code languages, "Swift", "Objective-c", "C" are the three elements, but there is no "Java" element. The results of the operation are as follows:

    • Languages the sequence contains the element "Swift"
    • Languages the sequence does not contain the element "Java"

When comparing, the case of letters is distinguished. So, strings of different capitalization are different.

Swift2.0 sequence sort function sortinplace ()

In programming, it is often necessary to sort elements in a sequence. This can be accomplished using the sortInPlace () function in Swift. Its grammatical form is as follows:

    • Sequence. sortInPlace ()

Where the sequence is an exponential group.

Example 7-23 the following will use the sort () function to sort the languages and value arrays. The code is as follows:

    • Import Foundation
    • var languages = ["Swift", "Objective-c", "C"]
    • Print ("Before sorting: languages=\ (Languages)")
    • Languages.sortinplace ()
    • Print ("After sorting: languages=\ (Languages)")

The results of the operation are as follows:

    • Before sorting: Languages=[swift, Objective-c, C]
    • After sorting: Languages=[c, Objective-c, Swift]

Swift2.0 sequence Reverse function reverse ()

The reverse () function can arrange the reverse order of elements in a sequence. Its grammatical form is as follows:

    • Sequence. Reverse ()

Where the sequence is an exponential group.

"Example 7-24" The following will use the reverse function to sort the sequence languages and value in reverse order. The code is as follows:

    • Import Foundation
    • var languages = ["Swift", "Objective-c", "C"]
    • Print ("Languages=\ (Languages)")
    • Print ("Reverse output:")
    • For I in Array (Languages.reverse ()) {
    • Print (i)
    • }
    • var value = [1,8,4,10]
    • Print ("value=\ (value)")
    • Print ("Reverse output:")
    • For I in Array (Value.reverse ()) {
    • Print (i)
    • }

The results of the operation are as follows:

    • Languages=[swift, Objective-c, C]

Reverse output:

    • C
    • Objective-c
    • Swift
    • Value=[1, 8, 4, 10]

Reverse output:

    • 10
    • 4
    • 8
    • 1

This article is selected from: Swift2.0 Language Quick Start v3.0 University bully Internal information, reproduced please indicate the source, respect the technology respect it people!

Swift2.0 The return value and function type of the function of the language tutorial

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.