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

/*
  函数(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(1, 10)) // 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 = 0
	var consonants = 0
	var others = 0
	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(1, 2, 3, ,4 5) // return 3.0
arithmeticMean(1, 2, 3) // return 2.0

// 常量和变量参数
// 在函数参数列表中,如果没有指定参数是常量还是变量,那么默认是let,即常量
// 这里Str需要在函数体内修改,所以需要指定为变量类型,即用关键字var
func alignRight(var str: String, count: Int, pad: Character) -> String {
  let amountToPad = count - countElements(str)

  // 使用_表示忽略,因为这里没有使用到
  for _ in 1...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 = 3
var second = 4
// 这种方式会修改实参的值
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(1, 2) // return 3
mathFunction = multiplyTwoInts
mathFunction(1, 2) // return 2

// 参数可以作为参数
func printMathResult(mathFunction: (Int, Int) -> Int, first: Int, second: Int) {
  println("Result: \(mathFunction(first, second))")
}

printMathResult(addTwoInts, 3, 5) // prints "Result: 8"
printMathResult(multiplyTwoInts, 3, 5) // prints "Result: 15"

// 函数作为返回类型
func stepForward(input: Int) -> Int {
  return input + 1
}

func stepBackward(intput: Int) -> Int {
  return input - 1
}

func chooseStepFunction(backwards: Bool) -> ((Int) -> Int) {
  return backwards ? stepBackward : stepForward
}

var currentValue = 3
let moveNearerToZero = chooseStepFunction(currentValue > 0) // call stepBackward() function

// 参数可以嵌套定义,在C、OC中是不可以嵌套的哦
func chooseStepFunction(backwards: Bool) -> ((Int) -> Int) {
  func stepForward(input: Int) -> Int {
    return input + 1
  }

  func stepBackward(input: Int) -> Int {
    return input + 1
  }

  return backwards ? stepBackward : stepForward
}
时间: 2024-08-01 14:20:28

Swift学习之十三:函数(Functions)的相关文章

最新Swift学习教程-从简单到复杂 韩俊强的博客

GitHub每日更新地址: https://github.com/iOS-Swift-Developers/Swift Swift基础知识大全,Swift学习从简单到复杂,不断地完善与更新, 欢迎Star️,欢迎Fork,️iOS开发者交流群:446310206 知识架构: 常两变量 基本数据类型 类型转换 Bool类型 元祖 可选值 字符和字符串 字符串常用方法 运算符 数组基本使用 数组其它操作 字典 if while for break-continue Switch 函数定义 函数参数

swift学习文档(笔记)_Swift

Swift是供iOS和OS X应用编程的新编程语言,基于C和Objective-C,而却没有C的一些兼容约束.Swift采用了安全的编程模式和添加现代的功能来是的编程更加简单.灵活和有趣.界面则基于广受人民群众爱戴的Cocoa和Cocoa Touch框架,展示了软件开发的新方向. 变量与常量 变量定义使用var,常量使用let,类型安全,有自动类型推导,注意赋值的=号两边必须有空格.变量和常量名是可以几乎所有字符,这些都非常像javascript.中文编程一下牛逼了. var a = 123 /

Swift学习资源

Swift,一种强大的开源编程语言, 让大家都能开发出众的 App. Swift 是一种强劲而直观的编程语言,它由 Apple 创造,可用来为 iOS.Mac.Apple TV 和 Apple Watch 开发 app.它旨在为开发者提供充分的自由.Swift 易用并且开源,只要有想法,谁都可以创造非凡. Swift is a high-performance system programming language. It has a clean and modern syntax, offer

求问ios大神swift学习流程

问题描述 求问ios大神swift学习流程 本人计算机大学生一枚,有过肤浅的php开发经验,现在想认真学一门语言,选择了swift,但是遇到了一些问题,首先是swift2.0资源弄不到,还有就是出了单纯的看书敲代码不知道怎么学习,求师傅传授 解决方案 目前对于ios学习的话,建议先学习使用oc开发ios,等基础扎实再向swift转型,转型速度是非常快的(两周左右可比较完善) 如果坚持直接学swift,想要较全面的了解常用基础的话,可以考虑下培训机构,因为国内的swift交流非常稀少,很难帮助学习

Swift语法专题七——函数

Swift讲解专题七--函数 一.引言         函数是有特定功能的代码段,函数会有一个特定的名称调用时来使用.Swift提供了十分灵活的方式来创建与调用函数.事实上在Swift,每个函数都是一种类型,这种类型由参数和返回值来决定.Swift和Objective-C的一大区别就在于Swift中的函数可以进行嵌套. 二.函数的创建与调用         函数通过函数名,参数和返回值来定义,参数和返回值决定一个函数的类型,在调用函数时,使用函数名来进行调用,示例如下: //传入一个名字 打印并

Swift学习笔记(一)搭配环境以及代码运行成功

原文:Swift学习笔记(一)搭配环境以及代码运行成功 1.Swift是啥? 百度去!度娘告诉你它是苹果最新推出的编程语言,比c,c++,objc要高效简单.能够开发ios,mac相关的app哦!是苹果以后大力推广的语言哦!   2.Swift给你带来什么机会? 当初你觉得objc太难,学ios学到一半放弃拉,或者进入it行业大家都搞android,你也搞android去了.现在你终于有机会和搞ios的站在一个语言的起跑线上,兄弟!swift传说很容易学哦,搞android的你想不想增加一下本领

Swift 3 中的函数参数命名规范指北

本文讲的是Swift 3 中的函数参数命名规范指北, 昨天,我开始将这个 Jayme 迁移到 Swift 3.这是我第一次将一个项目从 Swift 2.2 迁移至 Swift 3.说实话这个过程十分的繁琐,由于 Swift 3 在老版本基础上发生了很多比较大的改变,我不得不承认眼前这样一个事实,除了花费较多的时间以外,没有其余的捷径可走.不过这样的经历也带来一点好处:我对 Swift 3 的理解变得更为深入,对我来讲,这可能是最好的消息了. 在迁移代码的过程中,我需要做出很多的选择.更为蛋疼的是

Swift学习笔记(3)iOS 9 中的网络请求

Swift学习笔记(3)iOS 9 中的网络请求 目录 Swift学习笔记3iOS 9 中的网络请求 目录 编码方法 请求方法 其他修改 完整代码 运行结果 编码方法 在iOS9中,以前常用的stringByAddingPercentEscapesUsingEncoding方法被废除了,取而代之的是stringByAddingPercentEncodingWithAllowedCharacters方法. 用法示例: var strURL=String(format:"http://blog.cs

Swift学习笔记(2)网络数据交换格式(XML,JSON)解析 [iOS实战 入门与提高卷]

Swift学习笔记(2)网络数据交换格式(XML,JSON)解析 参考书籍及资源:iOS实战 入门与提高卷 关东升 参考书籍地址 用NSXML来解析XML文档 用TBXML来解析XML文档 用NSJSONSerialization来解析JSON文档 目录 Swift学习笔记2网络数据交换格式XMLJSON解析 目录 用NSXML来解析XML文档 示例文档Notesxml 创建XMLParser类 调用与运行结果 用TBXML来解析XML文档 准备工作 创建XMLParser类 调用与运行结果 用