迅捷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 + xreturn 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 " + namefunc 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 625exponentialFunction(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 = 0for 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 4result = 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

迅捷cad_迅捷功能相关推荐

  1. 迅捷cad_迅捷协议

    迅捷cad Continuing with our series of Swift tutorials, we'll be discussing and playing around with ano ...

  2. 迅捷cad_迅捷结构

    迅捷cad In this tutorial, we'll be discussing an important building block in Swift, namely Structures. ...

  3. 迅捷cad_迅捷数组

    迅捷cad In this tutorial, we'll be discussing about Swift Array. If you don't know how Optional in Swi ...

  4. 迅捷cad_迅捷泛型

    迅捷cad In this tutorial, we'll be discussing Generics in Swift. We'll be seeing how we can extend Gen ...

  5. 迅捷cad_迅捷属性

    迅捷cad In this tutorial, we'll be discussing about Swift Properties. Properties are an important part ...

  6. 迅捷cad_迅捷元组

    迅捷cad Swift tuple is a container to hold multiple values. Swift Arrays are largely homogeneous data ...

  7. 迅捷cad_迅捷套装

    迅捷cad In this tutorial, we'll be discussing the use cases of Swift Set. We'll look at the basic synt ...

  8. CAD转换技巧篇,安装迅捷CAD转换器的后续操作!

    作为办公室一名设计师助手,常常都要对各种格式的图纸进行转换,而且需要转换的文件非常多,电脑上转换的软件都会安装好几个.这时候你肯定会想,如果有一个软件能帮你把各种格式相互转换该多好,其实有这样的软件, ...

  9. 一种方便快速的在线制作流程图的软件-迅捷画图

    个人中心 - 迅捷画图迅捷画图网提供在线绘图与文件在线存储功能,您可随时随地进入个人中心查看和下载创建过的绘图文件,并且不用担心文件丢失问题.https://huatu.98youxi.com/hom ...

最新文章

  1. Bootstrap4 glyphicon 移除图标 glyphicon fonts-faces 解决方案
  2. 模糊数学笔记:七、模糊综合评判决策
  3. 3.爱跑步的蜗壳人动态(下同)
  4. 信号分解:标架、对偶标架、紧标架
  5. Makefile的call函数
  6. WIN8将IE设置为默认浏览器
  7. 读取 wps_软件前世今生篇之WPS(求伯君1988年先于OFFICE研发出WPS)
  8. Homebrew OS X 不可或缺的套件管理器
  9. hp服务器如何ghost系统,惠普(HP)电脑安装不了GHOST系统的解决办法
  10. IE的@cc_on条件编译
  11. 一口气说出8种幂等性解决重复提交的方案,面试官懵了!(附代码)
  12. 免费的分区软件MiniTool Partition Wizard Free
  13. 不需要appuploader破解版,也能上架
  14. 社会的需求对科技进步的作用要超过十所大学
  15. 计算机取证的相关案例,计算机取证案例分析
  16. 北京 php 外包,=== | php外包与php技术服务商
  17. C# 插入或删除word分页符
  18. C语言实现贪吃蛇(四)----游戏存档读档(文件操作)
  19. 466. 回文日期 Java题解 (模拟)
  20. C# - 音乐小闹钟_BetaV1.0

热门文章

  1. 2-9 prev + next选择器 “远亲不如近邻” 返回且只返回唯一-个元素。 而通过prev + next选择器就可以查找与“prev”元素紧邻的下一个“next”元素...
  2. 转-ios设备唯一标识获取策略
  3. 【原创】软件团队建设和管理--之我见
  4. [转载] Python中不可变集合的使用frozenset()方法
  5. [转载] Python Numpy
  6. [转载] 使用python 中的numpy创建数组
  7. transient是干嘛的
  8. [译]GLUT教程 - 重整子窗体
  9. 批处理 Telnet 星球大战 话说我也清楚这是什么东东
  10. 离开,是一个新的开始