/*
函数(Function)
函数是为执行特定功能的自包含的代码块。函数需要给定一个特定标识符(名字),然后当需要的时候,
就调用此函数来执行功能。
*/
// 函数的定义与调用
// 定义函数时,使用关键字func,返回值类型通过->指明,如下:
// 函数名:sayHello,
// 参数列表中只有一个参数,叫personName,参数类型是String
// 函数返回值类型:String
func sayHello(personName: String) -> String {
let greeting = "Hello, " + personName + "!"
return greeting
} // 函数调用
println(sayHello("Anna")) // prints "Hello, Anna"
println(sayHello("Brian")) // prints "Hello, Brian" // 简化函数体
func sayHelloAgain(personName: String) -> String {
return "Hello, " + personName + "!"
} println(sayHelloAgain("Anna")) // 函数可以有多个参数
/*!
* @brief 返回两个值的差
* @param start Int类型,范围区间的起点
* @param end Int类型,范围区间的终点
* @return 返回值为Int类型,表示终点-起点的值
*/
func halfOpenRangeLength(start: Int, end: Int) -> Int {
return end - start
}
println(halfOpenRangeLength(, )) // prints "9" // 无参数函数
func sayHelloWorld() -> String {
return "Hello, world"
}
println(sayHelloWorld()) // 无返回值的函数,其实这里没有指定返回值,也会返回一个特殊的值,Void
func sayGoodbye(personName: String) {
println("Goodbye, \(personName)!")
}
sayGoodbye("David") // 函数返回值是可以忽略的
func printAndCount(stringToPrint: String) -> Int {
println(stringToPrint)
return countElements(stringToPrint) // 计算字符串的长度
} // 不带返回值
func printWithoutCounting(stringToPrint: String) {
printAndCount(stringToPrint)
} printAndCount("Hello,world")
printWithoutCounting("hello, world") /*
* @brief 函数可以返回元组(多个值)
* @param string 字符串
* @return (vowels: Int, consonants: Int, others: Int)
* vowels:元音, consonants:辅音,others:其它字符
*/
func count(string: String) ->(vowels: Int, consonants: Int, others: Int) {
var vowels =
var consonants =
var others =
for c in string {
switch String(c).lowercaseString {
case "a", "o", "e", "i", "u":
++vowels
case "b", "c", "d", "f", "g", "h", "j", "k", "l", "m", "n",
"p", "q", "r", "s", "t", "v", "w", "x", "y", "z":
++consonants
default:
++others
}
}
return (vowels, consonants, others)
} let total = count("some arbitrary string!")
println("\(total.vowels) vowels and \(total.consonants) consonants") // 外部参数名(External Parameter Names)
// 有时候使用外部参数名是很有用的,这直到提示的作用,就好像OC语法中的参数一样,见名知意
func someFunction(externalParameterName localParameterName: Int) {
// do something
} // 看例子:
func join(lhsString: String, rhsString: String, joiner:String) -> String {
return lhsString + joiner + rhsString
}
// 这里调用的时候,没有外部参数名
join("hello", "world", ",") // prints "hello,world" // 加上#号后,参数名与外部名相同,这是快捷方式
func join(#lhsString: String, #rhsString: String, #joiner:String) -> String {
return lhsString + joiner + rhsString
}
// 调用方式
join(lhsString: "hello", rhsString: "world", joiner: ",") // prints "hello,world" // 可以不使用快捷方式
func join(lhsString: String, rhsString: String, withJoiner joiner: String) -> String {
return lhsString + joiner + rhsString
}
join("hello", "world", withJoiner: ",")// prints "hello,world" // 函数参数默认值
// 参数参数可以提供默认值,但是默认值只能是参数列表的最后,也就是说
// 如果arg1提供默认值,后面的都需要提供默认值。
func join(#originalString: String, #destinationString: String, #withJoiner: String = " ") -> String {
return originalString + withJoiner + destinationString
}
join(originalString: "hello", destinationString: "world", withJoiner: "-") // prints "hello-world"
join(originalString: "hello", destinationString: "world") // prints "hello world" // 如果提供了参数默认值,Swift会自动把这个参数名也作为外部参数名
// 这里withJoiner相当于加上了#:#withJoiner
func join(lhsString: String, rhsString: String, withJoiner: String = " ") -> String {
return lhsString + withJoiner + rhsString
}
join("hello", "world", withJoiner: "-")// // prints "hello-world" // 可变参数
// 可变参数接受0个或者多个指定类型的值。可变参数使用...表示
// 函数最多只能有一个可变参数,并且如果有可变参数,这个可变参数必须出现在参数列表的最后
// 如果参数列表中有一或多个参数提供默认值,且有可变参数,那么可变参数也要放到所有最后一个
// 提供默认值的参数之后(先是默认值参数,才能到可变参数)
func arithmeticMean(numbers: Double...) -> Double {
var total = 0.0
for number in numbers {
total += number
}
return total / Double(numbers.count)
} arithmeticMean(, , , , ) // return 3.0
arithmeticMean(, , ) // return 2.0 // 常量和变量参数
// 在函数参数列表中,如果没有指定参数是常量还是变量,那么默认是let,即常量
// 这里Str需要在函数体内修改,所以需要指定为变量类型,即用关键字var
func alignRight(var str: String, count: Int, pad: Character) -> String {
let amountToPad = count - countElements(str) // 使用_表示忽略,因为这里没有使用到
for _ in ...amountToPad {
str = pad + str
} return str
} // 输入/输出参数
// 有时候,在函数体内修改了参数的值,如何能直接修改原始实参呢?就是使用In-Out参数
// 使用inout关键字声明的变量就是了
// 下面这种写法,是不是很像C++中的传引用?
func swap(inout lhs: Int, inout rhs: Int) {
let tmp = lhs
lhs = rhs
rhs = tmp
}
// 如何调用呢?调用的调用,对应的实参前面需要添加&这个符号
// 因为需要修改,所以一定是var类型的
var first =
var second =
// 这种方式会修改实参的值
swap(&first, &second) // first = 4, second = 3 // 使用函数类型
// 这里是返回Int类型
// 参数类型是:(Int, Int) -> Int
func addTwoInts(first: Int, second: Int) -> Int {
return first + second
}
// 参数类型是:(Int, Int) -> Int
func multiplyTwoInts(first: Int, second: Int) -> Int {
return first * second
} var mathFunction: (Int, Int) -> Int = addTwoInts
mathFunction(, ) // return 3
mathFunction = multiplyTwoInts
mathFunction(, ) // return 2 // 参数可以作为参数
func printMathResult(mathFunction: (Int, Int) -> Int, first: Int, second: Int) {
println("Result: \(mathFunction(first, second))")
} printMathResult(addTwoInts, , ) // prints "Result: 8"
printMathResult(multiplyTwoInts, , ) // prints "Result: 15" // 函数作为返回类型
func stepForward(input: Int) -> Int {
return input +
} func stepBackward(intput: Int) -> Int {
return input -
} func chooseStepFunction(backwards: Bool) -> ((Int) -> Int) {
return backwards ? stepBackward : stepForward
} var currentValue =
let moveNearerToZero = chooseStepFunction(currentValue > ) // call stepBackward() function // 参数可以嵌套定义,在C、OC中是不可以嵌套的哦
func chooseStepFunction(backwards: Bool) -> ((Int) -> Int) {
func stepForward(input: Int) -> Int {
return input +
} func stepBackward(input: Int) -> Int {
return input +
} return backwards ? stepBackward : stepForward
}

使用函数类型

在 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. (七)json序列化

    在spring boot项目中已经包含有json序列化的框架,具体在包com.fasterxml.jackson.annotation中,建议看看详细源码. 但在项目应用上还是会有一些坑会出现的,举个 ...

  2. yii学习笔记(6),数据库操作(增删改)

    数据库增删改操作通过活动记录实例来完成 插入记录 /* ----------添加记录---------- */ // 创建活动记录对象 $article = new Article(); $artic ...

  3. Hbase过滤器

    Hbase过滤器简介 HBase的基本API,包括增.删.改.查等,增.删都是相对简单的操作,与传统的RDBMS相比,这里的查询操作略显苍白,只能根据特性的行键进行查询(Get)或者根据行键的范围来查 ...

  4. c语言中 *p++ 和 (*p)++ 有什么区别?以及C语言运算符的优先级。整理。

    *p++是指下一个地址. (*p)++是指将*p所指的数据的值加一. C编译器认为*和++是同优先级操作符,且都是从右至左结合的,所以*p++中的++只作用在p上,和*(p++)意思一样:在(*p)+ ...

  5. java 第八章 异常处理

    一.异常简介 (一)定义: 运行期间出现的错误,而不是编译时的语法错误 例如: 1.打开一个不存在的文件 2.网络连接中断 3.数学类错误 4.操作数组越界等 (二)异常的继承树 (三)异常类的体系结 ...

  6. C#使用API屏蔽系统热键和任务管理器

    最近做的一个winform类型的项目中需要屏蔽系统热键,在网上搜索了一下,基本上都是调用api来进行hook操作,下面的代码就可以完成功能 using System; using System.IO; ...

  7. 网络流Edmonds-Karp算法入门

    今天自习课没事干,看书自学了一下网络流中的EK算法.(求最大流) 设s为源点,t为汇点,C为容量矩阵,F为流量矩阵,f为最大流量. 1.初始化F,f 2.用BFS在残量网络中找到一条从s到t的最短增广 ...

  8. spring源码-BeanFactoryPostProcessor-3.2

    一.BeanFactoryPostProcessor这个是spring容器的拓展之一,其目的是在容器初始化完成之前,通过beanFactory对上下文进行进行操作. 二.常用场景,需要对beanDef ...

  9. CC3200底板测试-烧写CC3200-LAUNCHXL

    1. 拿到板子,先研究一下几个跳线帽的作用.我在底板上测到VCC_DCDC_3V3和VCC_BRD之间应该有一个跳线帽的,但是在原理上找不到. 2. LED灯的用途,测试的时候,发现这个灯有时候亮,有 ...

  10. Richardson成熟度模型

    Richardson Maturity Model(RMM) 迈向REST的辉煌 一个模型(由Leonard Richardson开发)将REST方法的主要元素分解为三个步骤.这些引入资源,http动 ...