Swift学习之十三:函数(Functions)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值