function (all you want to know is here)
Note: This article is summarized by the author himself. If it is too basic, I will not repeat it. It is the result of personal testing. If there are mistakes or omissions, please correct me and learn together.
1. Simple definition and invocation of functions
The simple parameterless function is no longer mentioned, name is a formal parameter, and it is also internally in several names.
func sayHello(name:String) ->String
{ return name+" say: hello" }
It's easysayHello("zhangsan")to call.
is not very simple ah!
2. External parameter name
What is the external parameter name, in fact, you give the formal parameter a meaningful alias, let others understand the purpose of this parameter.
func sayHello1(YourNmae name:String,name2:String) ->String
{
return name+" say: hello "+name2
}
Add this aliassayHello1(YourNmae: "zhangsan",name2:"lisi")when you call here.
Swift defaults from the second parameter to automatically add an external parameter name, equal to the internal argument name.
If you don't want to enter an external parameter name, you can underline it in front of you
// Ignore external parameter names
func add (a: Int, _ b: Int)-> Int
{
return a + b
}
add (1, 1) // 2
3. Parameter Default value
When the function passes in the parameter, it can give a default value, when the parameter is passed, the default value can be transmitted.
func plus(a:Int,another b:Int=0) -> Int
{
return a+b;
}
The default value for B here is 0, and when called, theprint(plus(1))result is 1, and theplus(1,another:2)result is 3.
4. Variable parameters
A mutable parameter (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. By adding (...) after the variable type name. To define a mutable parameter.
The value of the passed variable parameter is treated as an array of this type in the function body
func arithmeticMean(numbers: Double...) -> Double {
var total: Double = 0
for number in numbers {
total += number
}
return total / Double(numbers.count)
}
Here numbers is treated as an array toarithmeticMean(1,2,3,4,5.5)get the result 3.1
You can also pass a string or any other type
func say(name:String, content:String ... )
{
var str = name;
for item in content
{
str += item + " "
}
print(str)
}
Callsay("lily ", content:"like" ,"eat" ,"apple")result: Lily like eat apple
5. Constant parameters 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
I'm trying to modify the value of name here, I'm not allowed to modify the Let value
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.
At this point we need to define the variable parameters by adding the keyword var before the parameter name:
func say1(var name:String)->String
{
name += "2"
return name;
}
Call the function tosay1("wangwu")get the result: WANGWU2
6. Function type (functions Types)
What is a function type? In fact, each function has a specific type of function, which consists of the parameter type and the return type of the function. For examplesay1, the function type above is (String)->string, no parameter and return value ()---() returns a function of type void
Look at the void in Swift is actually an empty tuple
Let's see how the function type is used.
-
-
function type variable
var mySay:(String)->String = say1
Just like defining a normal variable, use the function type as a normal type, and heresay1is the function we wrote earlier.
Of course we can also take advantage of Swift's inference, not specifying the typevar mySay = say1
The call is the same as calling the normal functionmySay("hello")result: Hello2
- The
-
Function type is used as the parameter type
func sayWord(mySay:(String)->String , name:String)->String
{
return mySay(name)
}
Here we define a function that needs to pass in two parameters, the first parameter is a function type (String)->string, and finally a string is returned. When the
is called, we can give it a well-defined functionSayword (say1,name: "My"), Result: My2
We can also use closuresSayword ({"\ 2"}, Name: "My")results: My2
There are people here who may not know much about closures, but don't go into the next section.
-
-
function type as return type
Sometimes we need to use different functions in different situations, such as we need to pass a number, this number is greater than 0 using forward, less than 0 use backward, of course, here is just simple logic, can be done with If-else, But when the logic is very complicated, it can be written in two functions.
Take a look at the example:
func stepForward(input: Int) -> Int {
return input + 1
}
func stepBackward(input: Int) -> Int {
return input - 1
}
func chooseFunc(distance:Int) -> (Int)->Int
{
return distance>10 ? stepBackward:stepForward
}
This defines two very simple functions, or a function that selects a function based on the parameters passed in.
We are here to pass the function into the 8–14, the resulting function is passed in 10, see the change in this number, the result is:11 12 13 12 11 10 9this should be easy to understand
7. Return to tuple
Our function can also return a tuple type
func minMax( arr:Int ... )->(max:Int,min:Int)
{
var max = 0
var min = 0
for item in arr
{
if(item<max)
{
max = item
}
if(item>min)
{
min = item
}
}
return (max,min)
}
This is a very simple function, passing in a mutable parameter, and then finding the maximum and minimum values in this write. Invocation:minMax(2,3,5,88,98,-3)Result: (. 0-3,. 1 98)
Optional tuples-Sometimes we return a nil in our function, so this is what we need to write our tuples into an optional tuple.
Note: (Int, Int)? Is different from (Int?, Int?), (Int, Int)? Means that the entire tuple is optional, not that each element is optional
func mm()->(max:Int,min:Int)?
{
return nil
}
if let c = mm()
{
print("aa")
}else
{
print("bb")
}
This code finally outputs a BB
8, input and output parameters InOut
Declare the parameters of the function as inout this value can be modified in the function, and then replaced by the outgoing function of the original value, so you can not just pass in the literal address plus &
var myDate = 9
func normalFunc(var data:Int)
{
data = 100
}
normalFunc(myDate)
print(myDate) //9
func inoutFunc(inout data:Int)
{
data = 100
}
inoutFunc(&myDate)
print(myDate) //100
As you can see, the normal function does not change the value of the argument, and the inout changes back. When the transmission must be added &, in fact, will not add also can explode wrong.
9. Nested functions
You can define functions in other functions called nested functions nested functions are invisible to the outside world.
We can still play with the functions we just had.
func MychooseFunc(distance:Int) -> (Int)->Int
{
func stepBackward(input: Int) -> Int {
return input - 1
}
func stepForward(input: Int) -> Int {
return input + 1
}
return distance>10 ? stepBackward:stepForward
}
Temporarily first so many, later think of what to add, we can collect a dictionary, forget to check usage.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Swift's detailed three----------functions (all you want to know are here)