1. /*
  2. 函数(Function)
  3. 函数是为执行特定功能的自包含的代码块。函数需要给定一个特定标识符(名字),然后当需要的时候,
  4. 就调用此函数来执行功能。
  5. */
  6. // 函数的定义与调用
  7. // 定义函数时,使用关键字func,返回值类型通过->指明,如下:
  8. // 函数名:sayHello,
  9. // 参数列表中只有一个参数,叫personName,参数类型是String
  10. // 函数返回值类型:String
  11. func sayHello(personName: String) -> String {
  12. let greeting = "Hello, " + personName + "!"
  13. return greeting
  14. }
  15.  
  16. // 函数调用
  17. println(sayHello("Anna")) // prints "Hello, Anna"
  18. println(sayHello("Brian")) // prints "Hello, Brian"
  19.  
  20. // 简化函数体
  21. func sayHelloAgain(personName: String) -> String {
  22. return "Hello, " + personName + "!"
  23. }
  24.  
  25. println(sayHelloAgain("Anna"))
  26.  
  27. // 函数可以有多个参数
  28. /*!
  29. * @brief 返回两个值的差
  30. * @param start Int类型,范围区间的起点
  31. * @param end Int类型,范围区间的终点
  32. * @return 返回值为Int类型,表示终点-起点的值
  33. */
  34. func halfOpenRangeLength(start: Int, end: Int) -> Int {
  35. return end - start
  36. }
  37. println(halfOpenRangeLength(, )) // prints "9"
  38.  
  39. // 无参数函数
  40. func sayHelloWorld() -> String {
  41. return "Hello, world"
  42. }
  43. println(sayHelloWorld())
  44.  
  45. // 无返回值的函数,其实这里没有指定返回值,也会返回一个特殊的值,Void
  46. func sayGoodbye(personName: String) {
  47. println("Goodbye, \(personName)!")
  48. }
  49. sayGoodbye("David")
  50.  
  51. // 函数返回值是可以忽略的
  52. func printAndCount(stringToPrint: String) -> Int {
  53. println(stringToPrint)
  54. return countElements(stringToPrint) // 计算字符串的长度
  55. }
  56.  
  57. // 不带返回值
  58. func printWithoutCounting(stringToPrint: String) {
  59. printAndCount(stringToPrint)
  60. }
  61.  
  62. printAndCount("Hello,world")
  63. printWithoutCounting("hello, world")
  64.  
  65. /*
  66. * @brief 函数可以返回元组(多个值)
  67. * @param string 字符串
  68. * @return (vowels: Int, consonants: Int, others: Int)
  69. * vowels:元音, consonants:辅音,others:其它字符
  70. */
  71. func count(string: String) ->(vowels: Int, consonants: Int, others: Int) {
  72. var vowels =
  73. var consonants =
  74. var others =
  75. for c in string {
  76. switch String(c).lowercaseString {
  77. case "a", "o", "e", "i", "u":
  78. ++vowels
  79. case "b", "c", "d", "f", "g", "h", "j", "k", "l", "m", "n",
  80. "p", "q", "r", "s", "t", "v", "w", "x", "y", "z":
  81. ++consonants
  82. default:
  83. ++others
  84. }
  85. }
  86. return (vowels, consonants, others)
  87. }
  88.  
  89. let total = count("some arbitrary string!")
  90. println("\(total.vowels) vowels and \(total.consonants) consonants")
  91.  
  92. // 外部参数名(External Parameter Names)
  93. // 有时候使用外部参数名是很有用的,这直到提示的作用,就好像OC语法中的参数一样,见名知意
  94. func someFunction(externalParameterName localParameterName: Int) {
  95. // do something
  96. }
  97.  
  98. // 看例子:
  99. func join(lhsString: String, rhsString: String, joiner:String) -> String {
  100. return lhsString + joiner + rhsString
  101. }
  102. // 这里调用的时候,没有外部参数名
  103. join("hello", "world", ",") // prints "hello,world"
  104.  
  105. // 加上#号后,参数名与外部名相同,这是快捷方式
  106. func join(#lhsString: String, #rhsString: String, #joiner:String) -> String {
  107. return lhsString + joiner + rhsString
  108. }
  109. // 调用方式
  110. join(lhsString: "hello", rhsString: "world", joiner: ",") // prints "hello,world"
  111.  
  112. // 可以不使用快捷方式
  113. func join(lhsString: String, rhsString: String, withJoiner joiner: String) -> String {
  114. return lhsString + joiner + rhsString
  115. }
  116. join("hello", "world", withJoiner: ",")// prints "hello,world"
  117.  
  118. // 函数参数默认值
  119. // 参数参数可以提供默认值,但是默认值只能是参数列表的最后,也就是说
  120. // 如果arg1提供默认值,后面的都需要提供默认值。
  121. func join(#originalString: String, #destinationString: String, #withJoiner: String = " ") -> String {
  122. return originalString + withJoiner + destinationString
  123. }
  124. join(originalString: "hello", destinationString: "world", withJoiner: "-") // prints "hello-world"
  125. join(originalString: "hello", destinationString: "world") // prints "hello world"
  126.  
  127. // 如果提供了参数默认值,Swift会自动把这个参数名也作为外部参数名
  128. // 这里withJoiner相当于加上了#:#withJoiner
  129. func join(lhsString: String, rhsString: String, withJoiner: String = " ") -> String {
  130. return lhsString + withJoiner + rhsString
  131. }
  132. join("hello", "world", withJoiner: "-")// // prints "hello-world"
  133.  
  134. // 可变参数
  135. // 可变参数接受0个或者多个指定类型的值。可变参数使用...表示
  136. // 函数最多只能有一个可变参数,并且如果有可变参数,这个可变参数必须出现在参数列表的最后
  137. // 如果参数列表中有一或多个参数提供默认值,且有可变参数,那么可变参数也要放到所有最后一个
  138. // 提供默认值的参数之后(先是默认值参数,才能到可变参数)
  139. func arithmeticMean(numbers: Double...) -> Double {
  140. var total = 0.0
  141. for number in numbers {
  142. total += number
  143. }
  144. return total / Double(numbers.count)
  145. }
  146.  
  147. arithmeticMean(, , , , ) // return 3.0
  148. arithmeticMean(, , ) // return 2.0
  149.  
  150. // 常量和变量参数
  151. // 在函数参数列表中,如果没有指定参数是常量还是变量,那么默认是let,即常量
  152. // 这里Str需要在函数体内修改,所以需要指定为变量类型,即用关键字var
  153. func alignRight(var str: String, count: Int, pad: Character) -> String {
  154. let amountToPad = count - countElements(str)
  155.  
  156. // 使用_表示忽略,因为这里没有使用到
  157. for _ in ...amountToPad {
  158. str = pad + str
  159. }
  160.  
  161. return str
  162. }
  163.  
  164. // 输入/输出参数
  165. // 有时候,在函数体内修改了参数的值,如何能直接修改原始实参呢?就是使用In-Out参数
  166. // 使用inout关键字声明的变量就是了
  167. // 下面这种写法,是不是很像C++中的传引用?
  168. func swap(inout lhs: Int, inout rhs: Int) {
  169. let tmp = lhs
  170. lhs = rhs
  171. rhs = tmp
  172. }
  173. // 如何调用呢?调用的调用,对应的实参前面需要添加&这个符号
  174. // 因为需要修改,所以一定是var类型的
  175. var first =
  176. var second =
  177. // 这种方式会修改实参的值
  178. swap(&first, &second) // first = 4, second = 3
  179.  
  180. // 使用函数类型
  181. // 这里是返回Int类型
  182. // 参数类型是:(Int, Int) -> Int
  183. func addTwoInts(first: Int, second: Int) -> Int {
  184. return first + second
  185. }
  186. // 参数类型是:(Int, Int) -> Int
  187. func multiplyTwoInts(first: Int, second: Int) -> Int {
  188. return first * second
  189. }
  190.  
  191. var mathFunction: (Int, Int) -> Int = addTwoInts
  192. mathFunction(, ) // return 3
  193. mathFunction = multiplyTwoInts
  194. mathFunction(, ) // return 2
  195.  
  196. // 参数可以作为参数
  197. func printMathResult(mathFunction: (Int, Int) -> Int, first: Int, second: Int) {
  198. println("Result: \(mathFunction(first, second))")
  199. }
  200.  
  201. printMathResult(addTwoInts, , ) // prints "Result: 8"
  202. printMathResult(multiplyTwoInts, , ) // prints "Result: 15"
  203.  
  204. // 函数作为返回类型
  205. func stepForward(input: Int) -> Int {
  206. return input +
  207. }
  208.  
  209. func stepBackward(intput: Int) -> Int {
  210. return input -
  211. }
  212.  
  213. func chooseStepFunction(backwards: Bool) -> ((Int) -> Int) {
  214. return backwards ? stepBackward : stepForward
  215. }
  216.  
  217. var currentValue =
  218. let moveNearerToZero = chooseStepFunction(currentValue > ) // call stepBackward() function
  219.  
  220. // 参数可以嵌套定义,在C、OC中是不可以嵌套的哦
  221. func chooseStepFunction(backwards: Bool) -> ((Int) -> Int) {
  222. func stepForward(input: Int) -> Int {
  223. return input +
  224. }
  225.  
  226. func stepBackward(input: Int) -> Int {
  227. return input +
  228. }
  229.  
  230. return backwards ? stepBackward : stepForward
  231. }

使用函数类型

在 Swift 中,使用函数类型就像使用其他类型一样。例如,你可以定义一个类型为函数的常量或变量,并将函数赋值给它:

var mathFunction: (Int, Int) -> Int = addTwoInts

这个可以读作:

“定义一个叫做 mathFunction 的变量,类型是‘一个有两个 Int 型的参数并返回一个 Int 型的值的函数’,并让这个新变量指向 addTwoInts 函数”。

addTwoInts 和 mathFunction 有同样的类型,所以这个赋值过程在 Swift 类型检查中是允许的。

函数类型作为参数类型也可以作为返回类型,如上代码

Swift-函数的理解的更多相关文章

  1. Swift函数编程之Map、Filter、Reduce

    在Swift语言中使用Map.Filter.Reduce对Array.Dictionary等集合类型(collection type)进行操作可能对一部分人来说还不是那么的习惯.对于没有接触过函数式编 ...

  2. opengl中对glOrtho()函数的理解

    glOrtho是创建一个正交平行的视景体. 一般用于物体不会因为离屏幕的远近而产生大小的变换的情况.比如,常用的工程中的制图等.需要比较精确的显示. 而作为它的对立情况, glFrustum则产生一个 ...

  3. 回调函数透彻理解Java

    http://blog.csdn.net/allen_zhao_2012/article/details/8056665 回调函数透彻理解Java 标签: classjavastringinterfa ...

  4. 对c语言中malloc和free函数的理解

    最近在复习c语言的时候再次用到了malloc函数和free函数,此处着讲解一下自己对这两个函数的理解和认识. 一. malloc函数和free函数的基本概念和基本的用法 对于malloc函数: 1.  ...

  5. js中的回调函数的理解和使用方法

    js中的回调函数的理解和使用方法 一. 回调函数的作用 js代码会至上而下一条线执行下去,但是有时候我们需要等到一个操作结束之后再进行下一个操作,这时候就需要用到回调函数. 二. 回调函数的解释 因为 ...

  6. 如何在C语言中调用Swift函数

    在Apple官方的<Using Swift with Cocoa and Objectgive-C>一书中详细地介绍了如何在Objective-C中使用Swift的类以及如何在Swift中 ...

  7. Swift 函数

    1: 函数形式: Swift函数以关键字func 标示.返回类型->后写明.如果没有返回类型可以省去.多个参数用,分割.其中参数名字在前:类型描述 func GetName(strName:St ...

  8. swift函数的用法,及其嵌套实例

    import Foundation //swift函数的使用 func sayHello(name userName:String ,age:Int)->String{ return " ...

  9. JS匿名函数的理解

    js匿名函数的代码如下:(function(){ // 这里忽略jQuery 所有实现 })(); 半年前初次接触jQuery 的时候,我也像其他人一样很兴奋地想看看源码是什么样的.然而,在看到源码的 ...

  10. js回调函数(callback)理解

    Mark! js学习 不喜欢js,但是喜欢jquery,不解释. 自学jquery的时候,看到一英文词(Callback),顿时背部隐隐冒冷汗.迅速google之,发现原来中文翻译成回调.也就是回调函 ...

随机推荐

  1. 立个Flag (20180617-20181231)

    入行7年,今年年初正式接触Java,前面6年一直在做C++相关的工作,去年年中跳槽,语言从C++转向了C#,半年之后又转向了Java. 虽说语言有相似性,但每种语言都有自己独有的知识体系,想要游刃有余 ...

  2. 解决WinScp连接被拒绝的问题

    尝试以下方法: 1) 开启|关闭防火墙(这里需要关闭) sudo ufw enable|disable 2) 开启远程服务 在终端界面输入:service sshd start.结果显示:ssh:un ...

  3. CentOS 搭建 Git 服务器

    官方文档移步 Git 服务器的搭建 安装 Git #yum install git 创建 Git 专用用户 #useradd git,改密码 #passwd git,切换至 Git 用户 #su gi ...

  4. Java设计模式(23)——行为模式之访问者模式(Visitor)

    一.概述 概念 作用于某个对象群中各个对象的操作.它可以使你在不改变这些对象本身的情况下,定义作用于这些对象的新操作. 引入 试想这样一个场景,在一个Collection中放入了一大堆的各种对象的引用 ...

  5. 从官网下载centos

    今天想从官网下载6.5版本的CentOS,结果找了好一会儿才找到,赶紧记录下来,以备以后查询. 第一步在百度搜索centos,点击"Download CentOS",如下图所示. ...

  6. BZOJ1012_Maxnumber_KEY

    题目传送门 这是一道单调栈的问题,单调栈维护所有数的最大值. 查询操作时只需要二分找答案即可,枚举栈内的数应该也不会超时. code: /******************************* ...

  7. python之Queue

    一.多进程的消息队列 “消息队列”是在消息的传输过程中保存消息的容器 消息队列最经典的用法就是消费者和生成者之间通过消息管道来传递消息,消费者和生成者是不通的进程.生产者往管道中写消息,消费者从管道中 ...

  8. netty之管道处理流程

    1.我们在使用netty的是有都会存在将channelBuffer的数据处理成相应的String或者自定义数据.而这里主要是介绍管道里面存在的上行和下行的数据处理方式 2.通过一张图片来看一下具体管道 ...

  9. Updating Homebrew... 长时间不动解决方法

    确保你已安装Homebrew 依次输入下面的命令(注意:不要管重置部分的命令,这里原作者贴出来.我也贴出来是以防需要重置的时候有参考操作命令) 替换brew.git: cd "$(brew ...

  10. OpenCV 3.0.0处理鱼眼镜头信息 - Fisheye camera model

    此篇随笔主要参考OpenCV 3.0.0的官方文档翻译而来,主要用作理解OpenCV对鱼眼相机的标定.图像校正.3D重建功能的理解. 版权所有,转载请注明出处~ xzrch@2018.09.29 参考 ...