Swift4 基础部分:Functions

本文是学习《The Swift Programming Language》整理的相关随笔,基本的语法不作介绍,主要介绍Swift中的一些特性或者与OC差异点。

系列文章:

Defining and Calling Functions

这一节主要讲解Swift中的函数,Swift中函数的定义直接看一下官方例子一目了然。

例子:

func greet(person: String) -> String {
    let greeting = "Hello, " + person + "!"
    return greeting
}
print(greet(person: "Arnold"));

执行结果:

Hello, Arnold!

多返回值函数(Functions with Multiple Return Values)

You can use a tuple type as the return type for a function to return multiple values as part of one compound return 
value.
  • SWift中的函数的返回值可以是一个元组类型数据。

例子:

func minMax(array:[Int]) -> (min:Int,max:Int)?{
    if array.isEmpty{
        return nil;
    }
    var min = array[0];
    var max = array[0];
    
    for value in array[1..<array.count]{
        if value < min{
            min = value;
        }else if value > max{
            max = value;
        }
    }
    
    return (min,max)
}

if let (min,max) = minMax(array: [2,5,3,1,6]){
    print("min:\(min),max:\(max)");
}

执行结果:

min:1,max:6

注意可选型的使用,保证安全性

指定参数标签(Specifying Argument Labels)

You write an argument label before the parameter 
name,separated by a space
  • Swift的函数中可以在参数名的前面以空格隔开加入参数标签

例子:

func greet(person: String, from hometown: String) -> String {
    return "Hello \(person)!  Glad you could visit from \(hometown)."
}

print(greet(person: "Bill", from: "Cupertino")) 

执行结果:

Hello Bill!  Glad you could visit from Cupertino.

默认参数值(Default Parameter Values)

You can define a default value for any parameter in a 
function by assigning a value to the parameter after that 
parameter’s type. If a default value is defined, you can 
omit that parameter when calling the function.
  • 函数中的参数如果需要默认的值可以直接写在参数之后
func someFunction(parameterWithoutDefault: Int, parameterWithDefault: Int = 12) {
    print("parameterWithoutDefault \(parameterWithoutDefault),parameterWithDefault \(parameterWithDefault)");
}

someFunction(parameterWithoutDefault: 3, parameterWithDefault: 6);
someFunction(parameterWithoutDefault: 4);

执行结果:

parameterWithoutDefault 3,parameterWithDefault 6
parameterWithoutDefault 4,parameterWithDefault 12

可变参数(Variadic Parameters)

A variadic parameter accepts zero or more values of a 
specified type. You use a variadic parameter to specify 
that the parameter can be passed a varying number of input 
values when the function is called. Write variadic 
parameters by inserting three period characters (...) 
after the parameter’s type name.
  • Swift中引入了可变参数的概念,参数后加入...即可表示,该类型的数据可以传入0或者多个

例子:

func calculate(_ numbers: Double...) -> (Double){
    var sum :Double = 0.0;
    for var number in numbers{
        sum += number;
    }
    return sum;
}

print("sum:\(calculate(1,2,3,4,5))");

执行结果:

sum:15.0

In-Out Parameters

Function parameters are constants by default. Trying to 
change the value of a function parameter from within the 
body of that function results in a compile-time error. 
This means that you can’t change the value of a parameter 
by mistake. If you want a function to modify a parameter’s value, and you want those changes to persist after the 
function call has ended, define that parameter as an in-
out parameter instead.
  • 函数的参数默认都是常量定义的,如果需要函数内部更改参数的值需要将参数用inout修饰

例子:

func swapTwoInts(_ a: inout Int, _ b: inout Int) {
    let temporaryA = a
    a = b
    b = temporaryA
}
var a:Int = 1;
var b:Int = 2;
swap(&a, &b);
print("a:\(a),b:\(b)");

执行结果:

a:2,b:1

函数作为参数(Function Types as Parameter Types)

You can use a function type such as (Int, Int) -> Int as a 
parameter type for another function. This enables you to 
leave some aspects of a function’s implementation for the 
function’s caller to provide when the function is called. 

例子:

func add(_ firstNum:Int,_ secondNum:Int) -> Int{
    return firstNum + secondNum;
}

func minus(_ firstNum:Int,_ secondNum:Int) -> Int{
    return firstNum - secondNum;
}

func calculate(_ calculateFunction:(Int,Int) -> Int,_ firstNum:Int,_ secondNum:Int) -> Int{
    return calculateFunction(firstNum,secondNum);
}

print("add \(calculate(add,3,2))");
print("minus \(calculate(minus,3,2))");

执行结果:

add 5
minus 1

函数作为返回值(Function Types as Return Types)

You can use a function type as the return type of another 
function. You do this by writing a complete function type 
immediately after the return arrow (->) of the returning 
function.

例子:

func add(_ firstNum:Int,_ secondNum:Int) -> Int{
    return firstNum + secondNum;
}

func minus(_ firstNum:Int,_ secondNum:Int) -> Int{
    return firstNum - secondNum;
}

func calculator(_ isAdd:Bool) -> (Int,Int) -> Int{
    return isAdd ? add : minus;
}

var invokeCalculator = calculator(true);
print("add \(invokeCalculator(1,2))");
invokeCalculator = calculator(false);
print("minus \(invokeCalculator(3,2))");

执行结果:

add 3
minus 1

内嵌函数(Nested Functions)

直接看一个例子,把上一个例子中的addFunction,minusFunction放到calculator中即可。

例子:

func calculator(_ isAdd:Bool) -> (Int,Int) -> Int{
    
    func add(_ firstNum:Int,_ secondNum:Int) -> Int{
        return firstNum + secondNum;
    }
    
    func minus(_ firstNum:Int,_ secondNum:Int) -> Int{
        return firstNum - secondNum;
    }
    
    return isAdd ? addFunction : minusFunction;
}

var invokeCalculator = calculator(true);
print("add \(invokeCalculator(1,2))");
invokeCalculator = calculator(false);
print("minus \(invokeCalculator(3,2))");

执行结果:

add 3
minus 1
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 160,108评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,699评论 1 296
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,812评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,236评论 0 213
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,583评论 3 288
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,739评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,957评论 2 315
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,704评论 0 204
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,447评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,643评论 2 249
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,133评论 1 261
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,486评论 3 256
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,151评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,108评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,889评论 0 197
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,782评论 2 277
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,681评论 2 272

推荐阅读更多精彩内容

  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 11,623评论 4 59
  • 转载自:https://github.com/Tim9Liu9/TimLiu-iOS[https://github...
    香橙柚子阅读 8,125评论 0 35
  • 版本记录 前言 我是swift2.0的时候开始接触的,记得那时候还不是很稳定,公司的项目也都是用oc做的,并不对s...
    刀客传奇阅读 1,063评论 0 0
  • 2014.3.15.@桉木的文 刚看到一篇很久以前写的文章,看了很好笑,但心也有点酸。 有人说:暗恋是恋爱中最美好...
    吕桉木阅读 816评论 2 5
  • 我喜欢不带目的地游走于这人世间,这样遇到的人碰到的景都将是惊喜。我喜欢惊喜。失去惊喜我就不知道如何活。
    Messier42阅读 171评论 0 1