Swift_函数
Swift_函数
定义和调用函数
//定义和调用函数
func testDefiningAndCallingFunctions() {
func sayHello(_ personName: String) -> String {
let greeting = "Hello " + personName + "!"
return greeting
}
print(sayHello("XuBaoAiChiYu"))
/* print
Hello XuBaoAiChiYu!
*/
}
无参数函数
//无参数函数
func testFunctionsWithoutParameters() {
//无参数 只有一个String类型的返回值
func sayHelloWorld() -> String {
return "hello world!"
}
print(sayHelloWorld())
/* print
hello world!
*/
}
多参数函数
//多参数函数
func testFunctionsWithMultipleParameters() {
//传入两个参数 并返回一个String类型的数据
func sayHello(_ personName: String, alreadyGreeted: Bool) -> String {
if alreadyGreeted {
return "Hello again \(personName)!"
} else {
return "Hello \(personName)!"
}
}
print(sayHello("XuBaoAiChiYu", alreadyGreeted: true))
/* print
Hello again XuBaoAiChiYu!
*/
}
函数无返回值
//函数无返回值
func testFunctionsWithoutReturnValues() {
//传入一个String类型的数据 不返回任何数据
func sayGoodbye(_ personName: String) {
print("Goodbye \(personName)!")
}
sayGoodbye("XuBaoAiChiYu")
/* print
Goodbye XuBaoAiChiYu!
*/
}
函数多返回值
//函数多返回值
func testMultipleReturnValues() {
//返回一个Int类型的数据
func printAndCount(_ stringToPrint: String) -> Int {
print(stringToPrint)
return stringToPrint.characters.count
}
print(printAndCount("hello world"))
//返回元组合数据
func minMax(_ array: [Int]) -> (min: Int, max: Int) {
var currentMin = array[0]
var currentMax = array[0]
for value in array[1..<array.count] {
if value < currentMin {
currentMin = value
} else if value > currentMax {
currentMax = value
}
}
return (currentMin, currentMax)
}
let bounds = minMax([8, -6, 2, 109, 3, 71])
print("min is \(bounds.min) and max is \(bounds.max)")
/* print
hello world
11
min is -6 and max is 109
*/
}
返回类型可选
//返回类型可选
func testOptionalTupleReturnTypes() {
//返回一个元组或Nil
func minMax(_ array: [Int]) -> (min: Int, max: Int)? {
if array.isEmpty {
return nil
}
var currentMin = array[0]
var currentMax = array[0]
for value in array[1..<array.count] {
if value < currentMin {
currentMin = value
} else if value > currentMax {
currentMax = value
}
}
return (currentMin, currentMax)
}
if let bounds = minMax([8, -6, 2, 109, 3, 71]) {
print("min is \(bounds.min) and max is \(bounds.max)")
}
/* print
min is -6 and max is 109
*/
}
指定外部参数名
//指定外部参数名
func testSpecifyingExternalParameterNames() {
//指定外部参数名to和and
func sayHello(to person: String, and anotherPerson: String) -> String {
return "Hello \(person) and \(anotherPerson)!"
}
print(sayHello(to: "Bill", and: "Ted"))
/* print
Hello Bill and Ted!
*/
}
省略外部参数名
//省略外部参数名
func testOmittingExternalParameterNames() {
//使用 _ 省略外面参数名,
func someFunction(_ firstParameterName: Int, _ secondParameterName: Int) {
print("\(firstParameterName) and \(secondParameterName)")
}
someFunction(2, 3)
/* print
2 and 3
*/
}
默认参数值
//默认参数值
func testDefaultParameterValues() {
//设置默认值 当用户不传入时 使用默认值
func someFunction(_ parameterWithDefault: Int = 12) {
print("\(parameterWithDefault)")
}
someFunction(6)
someFunction()
/* print
6
12
*/
}
可变参数
//可变参数
func testVariadicParameters() {
//传入的参数类型已知Double 个数未知
func arithmeticMean(_ numbers: Double...) -> Double {
var total: Double = 0
for number in numbers {
total += number
}
return total / Double(numbers.count)
}
print("\(arithmeticMean(1, 2, 3, 4, 5))")
print("\(arithmeticMean(3, 8.25, 18.75))")
/* print
3.0
10.0
*/
}
常量和变量参数
//常量和变量参数
func testConstantAndVariableParameters() {
//默认为let常量参数 也可声明var可变参数 在函数内直接修改
func alignRight(_ string: String, totalLength: Int, pad: Character) -> String {
var string = string
let amountToPad = totalLength - string.characters.count
if amountToPad < 1 {
return string
}
let padString = String(pad)
for _ in 1...amountToPad {
string = padString + string
}
return string
}
let originalString = "hello"
let paddedString = alignRight(originalString, totalLength: 10, pad: "-")
print("originalString:\(originalString); paddedString:\(paddedString);")
/* print
originalString:hello; paddedString:-----hello;
*/
}
In-Out参数
//In-Out参数
func testInOutParameters() {
//使用inout声明的参数 在函数内修改参数值时 外面参数值也会变
func swapTwoInts(_ a: inout Int, _ b: inout Int) {
let temporaryA = a
a = b
b = temporaryA
}
var someInt = 3
var anotherInt = 107
swapTwoInts(&someInt, &anotherInt)
print("someInt is now \(someInt), and anotherInt is now \(anotherInt)")
/* print
someInt is now 107, and anotherInt is now 3
*/
}
使用函数类型
//使用函数类型
func testUsingFunctionTypes() {
//加法
func addTwoInts(_ a: Int, _ b: Int) -> Int {
return a + b
}
//乘法
func multiplyTwoInts(_ a: Int, _ b: Int) -> Int {
return a * b
}
// 函数体赋值为参数
var mathFunction: (Int, Int) -> Int = addTwoInts
print("Result: \(mathFunction(2, 3))")
// 函数体指向替换
mathFunction = multiplyTwoInts
print("Result: \(mathFunction(2, 3))")
// 函数体传递
let anotherMathFunction = addTwoInts
print("\(anotherMathFunction)")
/* print
Result: 5
Result: 6
(Function)
*/
}
函数做参数类型
//函数做参数类型
func testFunctionTypesAsParameterTypes() {
//加法
func addTwoInts(_ a: Int, _ b: Int) -> Int {
return a + b
}
//其中一个参数为一个函数体
func printMathResult(_ mathFunction: (Int, Int) -> Int, _ a: Int, _ b: Int) {
print("Result: \(mathFunction(a, b))")
}
printMathResult(addTwoInts, 3, 5)
/* print
Result: 8
*/
}
函数做返回类型
//函数做返回类型
func testFunctionTypesAsReturnTypes() {
//加1
func stepForward(_ input: Int) -> Int {
return input + 1
}
//减1
func stepBackward(_ input: Int) -> Int {
return input - 1
}
//使用函数体做返回类型
func chooseStepFunction(_ backwards: Bool) -> (Int) -> Int {
return backwards ? stepBackward : stepForward
}
var currentValue = 3
// 此时moveNearerToZero指向stepForward函数
let moveNearerToZero = chooseStepFunction(currentValue > 0)
// 调用函数体
currentValue = moveNearerToZero(currentValue)
print("\(currentValue)... ")
/* print
2...
*/
}
嵌套函数
//嵌套函数
func testNestedFunctions() {
//函数体内部嵌套函数 并做返回类型
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
}
var currentValue = -2
let moveNearerToZero = chooseStepFunction(currentValue > 0)
currentValue = moveNearerToZero(currentValue)
print("\(currentValue)... ")
/* print
-1...
*/
}
Swift_函数的更多相关文章
- Swift_类型选择
Swift_类型选择 点击查看源码 //类型选择 func test() { class MediaItem { } class Movie: MediaItem { } class Song: Me ...
- Swift_初始化
#Swift_初始化 点击查看源码 初始化结构体 //初始化结构体 func testInitStruct() { //结构体 类中默认方法 struct Size { //宽 var width = ...
- Swift_枚举
Swift_枚举 点击查看源码 空枚举 //空枚举 enum SomeEnumeration { // enumeration definition goes here } 枚举基本类型 //枚举基本 ...
- Swift_闭包
Swift_闭包 点击查看源码 闭包优化 //闭包优化 func testClosures() { //函数做参数 排序 let names = ["XuBaoAiChiYu", ...
- Python 小而美的函数
python提供了一些有趣且实用的函数,如any all zip,这些函数能够大幅简化我们得代码,可以更优雅的处理可迭代的对象,同时使用的时候也得注意一些情况 any any(iterable) ...
- 探究javascript对象和数组的异同,及函数变量缓存技巧
javascript中最经典也最受非议的一句话就是:javascript中一切皆是对象.这篇重点要提到的,就是任何jser都不陌生的Object和Array. 有段时间曾经很诧异,到底两种数据类型用来 ...
- JavaScript权威指南 - 函数
函数本身就是一段JavaScript代码,定义一次但可能被调用任意次.如果函数挂载在一个对象上,作为对象的一个属性,通常这种函数被称作对象的方法.用于初始化一个新创建的对象的函数被称作构造函数. 相对 ...
- C++对C的函数拓展
一,内联函数 1.内联函数的概念 C++中的const常量可以用来代替宏常数的定义,例如:用const int a = 10来替换# define a 10.那么C++中是否有什么解决方案来替代宏代码 ...
- 菜鸟Python学习笔记第一天:关于一些函数库的使用
2017年1月3日 星期二 大一学习一门新的计算机语言真的很难,有时候连函数拼写出错查错都能查半天,没办法,谁让我英语太渣. 关于计算机语言的学习我想还是从C语言学习开始为好,Python有很多语言的 ...
随机推荐
- Python入门-生成器和生成器表达式
昨天我们说了迭代器,那么和今天说的生成器是什么关系呢? 一.生成器 什么是生成器?说白了生成器的本质就是迭代器. 在Python中中有三种方式来获取生成器. 1.通过生成器函数 2.通过各种推导式来实 ...
- Java反射机制(带应用)
1.Java的反射机制: Java反射机制是在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法:对于任意一个对象,都能够调用它的任意一个方法和属性:这种动态获取的信息以及动态 ...
- XPath路径表达式笔记(转载)
简单说,xpath就是选择XML文件中节点的方法. 所谓节点(node),就是XML文件的最小构成单位,一共分成7种. - element(元素节点)- attribute(属性节点)- text ( ...
- postgres备份数据库
1. psql --help psql is the PostgreSQL interactive terminal. Usage: psql [OPTION]... [DBNAME [USERNAM ...
- 08_Redis持久化——RDB方式
[简述] 持久化:Redis能将数据从内存中以某种形式同步到硬盘中,使得重启后可以根据硬盘中的记录恢复数据,这一过程就是持久化. Redis支持两种方式的持久化,简单来说如下: RDB方式:会根据指定 ...
- ES6入门——正则的扩展
1.RegExp构造函数 在ES5中,RegExp构造函数的参数有两种情况.第一种情况是参数是字符串,这时第二个参数表示正则表达式的修饰符:第二种情况是,参数是一个正则表示式,这时会返回一个原有正则表 ...
- javascprit form表单提交前验证以及ajax返回json
1.今天要做一个手机验证码验证的功能.需求是前端页面点击发送 短信验证码,后台接收后通过ajax返回到前端,之后前端在提交时候进行验证.思路很简单,不过做的过程还是学到不少的东西. 1.ajax请求后 ...
- mvn 打包命令
mvn install & package:package是把jar打到本项目的target下,而install时把target下的jar安装到本地仓库,供其他项目使用. mvn clean ...
- 什么是shell? bash和shell有什么关系?
什么是Shell? shell是你(用户)和Linux(或者更准确的说,是你和Linux内核)之间的接口程序.你在提示符下输入的每个命令都由shell先解释然后传给Linux内核. ...
- writing a javascript module ready for ES6 import
javascript模块化是一个比较大也是比较容易混淆的topic.通常几乎所有的第三方Library都支持CMD,AMD,ES6,Global object方式来引用lib所暴露出来的服务. 那么如 ...