迅捷cad_迅捷功能

迅捷cad

In this swift function tutorial, we’ll be looking at how functions are defined and used in Swift. We’ll be covering all the concepts that’ll give you a deeper understanding and hopefully by the end of this tutorial you’d have mastered the concept of function in swift programming.

在本swift函数教程中,我们将研究如何在Swift中定义和使用函数。 我们将介绍所有概念,这些概念将使您有更深入的了解,并希望在本教程结束时您已精通快速编程中的函数概念。

迅捷功能 (Swift Function)

According to the Apple documentation, “Swift Functions are self-contained chunks of code that perform a specific task. You give a function a name that identifies what it does, and this name is used to “call” the function to perform its task when needed”.

根据Apple文档,“ Swift函数是执行特定任务的自包含代码块。 您为函数指定一个名称,该名称可以标识其功能,并且该名称用于“调用”该函数以在需要时执行其任务”。

We’ll be covering the following concepts in this tutorial.

在本教程中,我们将介绍以下概念。

  1. Named and Unnamed parameters

    命名和未命名参数
  2. Default parameter value

    默认参数值
  3. Multiple return types

    多种退货类型
  4. Inout parameters

    输入参数
  5. Variadic parameters

    可变参数
  6. Nested functions

    嵌套函数
  7. Functions as types, parameters and return type

    作为类型,参数和返回类型的函数

Let’s open up our Playground in XCode and dive right in!

让我们在XCode中打开Playground并直接进入!

定义和调用Swift函数 (Defining and Calling Swift Function)

To define a swift function, we need to start with the keyword func followed by the name of the function as shown below.

要定义一个快速函数,我们需要以关键字func开头,后跟函数名称,如下所示。

func helloFunction()
{
 print("Hello Swift Functions)
}

带参数和返回类型的Swift函数 (Swift Functions with parameters and return types)

Let’s define a swift function with parameters and see what it looks like.

让我们用参数定义一个swift函数,看看它是什么样子。

func display(websiteName w: String, withTutorial t: String)
{
   print(w + " " + t)
}

The code snippet inside the parenthesis can look intimidating at first. Let’s observe it closely.

括号内的代码片段乍一看可能令人生畏。 让我们仔细观察一下。

The parameters inside the above function consist of two parts. An external parameter followed by an internal parameter. Such type of parameters consisting of two labels are known as named parameters.

上述函数内部的参数由两部分组成。 外部参数后跟内部参数。 这种由两个标签组成的参数类型称为命名参数。

  1. The type of the parameter follows after the colon :.

    参数的类型在冒号之后:
  2. websiteName and withTutorial are the external parameters and shall be only used when calling the function. External parameters are also known as argument labels.

    websiteNamewithTutorial是外部参数,仅在调用函数时使用。 外部参数也称为参数标签。
  3. w and t are the internal parameters and would be used inside the body of the function. Internal parameters are also known as local parameters.

    wt是内部参数,将在函数体内使用。 内部参数也称为局部参数。

The above function is called in the following way.

上述功能按以下方式调用。

display(websiteName: "JournalDev", withTutorial: "Functions In Swift")

Swift function named parameters are useful in the essence that they indicate the purpose of the parameters in the functions through argument labels thereby reflecting what the function does in a clear way.

Swift函数命名参数在本质上很有用,因为它们通过参数标签指示函数中参数的用途,从而以清晰的方式反映函数的功能。

Another way of defining a function is given below.

下面给出了定义函数的另一种方法。

func appendStrings(a : String, b: String)
{
    print(a + " " + b)
}

appendStrings(a: "Hello", b:"Swift")

In the above code, we haven’t explicitly set the external and internal parameters. Swift considers them as both in the above case.

在上面的代码中,我们没有显式设置外部和内部参数。 Swift在上述情况下都将它们视为。

To omit the external parameter(argument label) explicitly, we need to add an underscore _.

要显式省略外部参数(参数标签),我们需要添加下划线_

Following code snippet demonstrates an example where the first parameter is unnamed.

下面的代码片段演示了第一个参数未命名的示例。

func appendString(_ a: String, with b: String)
{
  print(a + " " + b)   
}

appendString("Hello", with: "Swift")

Note: We cannot change the parameter value inside a function (At least not with the above approach).

注意 :我们不能在函数内部更改参数值(至少不能通过上述方法更改)。

Next, let’s create a function with a return type.

接下来,让我们创建一个带有返回类型的函数。

func sumOfTwo(_ a: Int, _ b:Int) -> Int
{
  return a + b
}
print(sumOfTwo(2,3))

To set a return type we’ve added the operator -> followed by the data type being returned.

要设置返回类型,我们添加了运算符->后跟要返回的数据类型。

A default value for any parameter in a function can be assigned after the parameter’s type. If a default value is defined, we can omit that parameter when calling the function.

可以在参数类型之后分配函数中任何参数的默认值。 如果定义了默认值,则可以在调用函数时忽略该参数。

Let’s create a function which has a default value set for a parameter as shown below

让我们创建一个为参数设置默认值的函数,如下所示

func sum(_ a:Int, _ b:Int = 2) -> Int
{
   return a + b
}
print(sum(5)) //Prints 7
print(sum(5, 3)) //Prints 8

Swift Function输入参数 (Swift Function inout parameters)

inout parameters: To change the value of a parameter such that the new value is persistent even after the function call is over we define the parameter as an inout. A code snippet below demonstrates a function with such parameter.

inout参数:要更改参数的值,以使新值在函数调用结束后仍保持不变,我们将参数定义为inout 。 下面的代码段演示了具有此类参数的功能。

var i = 3
print(i) //prints 3
func increment(_ i: inout Int, by x: Int) -> Int
{
    i = i + x
    return i
}
increment(&i, by: 3)
print(i) //prints 6

Constants can’t be passed as swift function inout parameters.

常量不能作为swift函数的inout参数传递。

Note: inout parameters are similar to passing by reference in C.

注意 :inout参数类似于在C中通过引用传递。

Swift函数可变参数 (Swift Function variadic parameters)

Swift function variadic parameter accepts zero or more values of a specified type. Only one variadic parameter is allowed per function. A variadic parameter is denoted by ... after the type of the parameter as shown below.

Swift函数可变参数接受零个或多个指定类型的值。 每个函数只允许使用一个可变参数。 可变参数在参数类型之后用...表示,如下所示。

func makeSentence( words: String...) -> String
{
    var sentence = ""
    for word in words
    {
     sentence = sentence + " " + word
    }
    return sentence
}

makeSentence(words: "Function","having", "Variadic parameters","Add as many strings here you want", "Can use one variadic parameter per func","Make full use")

Swift函数返回多个值 (Swift Function returning multiple values)

We can use a tuple type as the return type for a function to return multiple values as one compound value as shown below.

我们可以使用元组类型作为函数的返回类型,以将多个值作为一个复合值返回,如下所示。

func returnSentenceAndWordCount(_ strings: String...) -> (sentence: String, wordCount: Int)
{
    var sentence = ""
    for s in strings
    {
        sentence = sentence + " " + s
    }
    return (sentence, strings.count)
}

let data = returnSentenceAndWordCount("Function","returns a tuple", "containing", "sentence and number of strings and word count")
                                      
print(data.sentence + "\n\(data.wordCount)")

The tuple members are accessed using the dot operator on the returned type.

使用返回的类型上的点运算符访问元组成员。

Swift中的嵌套函数 (Nested Functions in Swift)

Swift allows us to define a function within a function as shown below.

Swift允许我们在一个函数内定义一个函数,如下所示。

func sayHello(to name: String) {
    let s = "Hello " + name
    func printString() {
        print(s)
    }
}
sayHello(to: "Anupam") //prints Hello Anupam

In the above code, the constant s is available to the nested function.

在上面的代码中,常量s可用于嵌套函数。

Swift函数作为类型,参数和返回类型 (Swift Functions as types, parameters and return types)

The parameter types and return types of functions can make up a custom independent data type that can be used smartly in Swift.

函数的参数类型和返回类型可以组成可在Swift中巧妙使用的自定义独立数据类型。

Besides, functions in Swift allows passing another function as a parameter or return type too. We’ll be implementing each of these below.

此外,Swift中的函数还允许将另一个函数作为参数或返回类型传递。 我们将在下面实现所有这些功能。

Let’s start by creating two basic functions as shown below.

让我们从创建两个基本函数开始,如下所示。

//Function to calculate square of an integer.
func square(_ num :Int)->Int
{
     return num*num
}
square(4) // returns 16

//Function to calculate cube of an integer.
func cube(_ num :Int)->Int
{
    return num*num*num
}
cube(4) // returns 64

We can assign a function to a variable/constant as shown below.

我们可以将函数分配给变量/常量,如下所示。

var exponentialFunction = square

exponentialFunction is defined as a variable which is of the type of a function that takes an Int parameter and returns an Int parameter.

exponentialFunction被定义为具有Int参数并返回Int参数的函数类型的变量。

We can now call the variable exponentialFunction as shown in the below code snippet.

现在,我们可以调用变量exponentialFunction ,如下面的代码片段所示。

exponentialFunction(4) //This would work the same way as square(4)

square(exponentialFunction(5)) //This would return 625

exponentialFunction(exponentialFunction(5)) //Same as above

We can change the type of exponentialFunction to the function cube as shown below.

我们可以将exponentialFunction的类型更改为function cube ,如下所示。

exponentialFunction = cube(_:)
square(exponentialFunction(5)) // square of cube of 5. returns 15625

Let’s create a function that accepts the above functions square and cube as parameters.

让我们创建一个接受上述函数square和cube作为参数的函数。

var integers = [1,2,3,4,5]

func sumOfExponentialsOf(array a: [Int], with function: (Int)->Int)->Int
{
    var result = 0
    for x in a
    {
        result = result + function(x)
    }
    return result   
}

The above function calculates the sum of function returned values for all array elements.

上面的函数计算所有数组元素的函数返回值的总和。

Tip : Swift is smart enough to infer the type of variable/constant from the value.

提示 :Swift足够聪明,可以根据值推断变量/常量的类型。

Note: The second parameter accepts a type (Int)->Int which is the same type as for exponentialFunction.

注意 :第二个参数接受类型(Int)->Int ,该类型与exponentialFunction类型相同。

We’ll use the above function to calculate the sum of squares and sum of cubes of all array elements as shown below.

我们将使用上述函数来计算所有数组元素的平方和和立方和,如下所示。

exponentialFunction = square(_:)
//sum of squares of all array elements
sumOfExponentialsOf(array: integers, with: exponentialFunction) // returns 55
exponentialFunction = cube(_:)
//sum of cubes of all array elements
sumOfExponentialsOf(array: integers, with: exponentialFunction) // returns 225

Lastly, it’s possible for a function to return another function. Let’s create a function that returns either the square or cube function based on a condition.

最后,一个函数有可能返回另一个函数。 让我们创建一个根据条件返回squarecube函数的函数。

func chooseComputation(isSquared b : Bool) -> (Int)->Int{

    func square(_ num :Int)->Int
    {
        return num*num
    }
    
    func cube(_ num :Int)->Int
    {
        return num*num*num
    }
    
    if b {
        return square
    }
    else{
        return cube
    }

}

var result = chooseComputation(isSquared: true)
result(2) //returns 4

result = chooseComputation(isSquared: false)
result(2) //returns 8

The chooseComputation function consists of two functions with the same type as of return.

chooseComputation函数由两个与return类型相同的函数组成。

Based on the boolean value the chooseComputation function returns a reference to either of the nested functions which are then referenced from the result variable.

基于布尔值, chooseComputation函数返回对两个嵌套函数的引用,然后从结果变量中对其进行引用。

Trying the above scenarios in your playground. Below is a screenshot from my playground.

在操场上尝试上述方案。 下面是我操场上的截图。

This brings an end to this tutorial. We’ve covered all the major usages of functions in Swift.

本教程到此结束。 我们已经介绍了Swift中函数的所有主要用法。

翻译自: https://www.journaldev.com/15126/swift-function

迅捷cad

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值