函数

func sayHello(name:String?) -> String{
    return "hello " + (name ?? "Guest")
}
sayHello("imooc")
var nickname: String? = nil
sayHello(nickname)

//没有返回值
func printHello() -> (){
    print("hello")
}
func printHello2() -> Void{
    print("hello")
}

使用元祖返回多个值

func findMaxAndMin( numbers: [Int]) -> (max:Int, min:Int)? {
//    if numbers.isEmpty{
//        return nil
//    }
    guard numbers.count > 0 else{
        return nil
    }
    var minValue = numbers[0]
    var maxValue = numbers[0]
    for number in numbers{
        minValue = minValue < number ? minValue : number
        maxValue = maxValue > number ? maxValue : number
    }
    return (maxValue, minValue)
}

var scores:[Int]? = [111, 232, 444, 133, 555, 289]//保证scores不是空的
scores = scores ?? []
if let result = findMaxAndMin( scores! ){
    print("The max score is \(result.max), The min score is \(result.min)")
}

命名

func sayHelloTo( name: String, greeting: String) -> String{
    return "\(greeting), \(name)"
}
sayHelloTo("Playground", greeting: "Hello")

func mutiply(num1:Int, _ num2:Int) -> Int{
    return num1*num2
}
mutiply(3, 3)

默认参数和可变参数

func sayHelloTo(name: String, withGreetingWord greeting:String = "hello", punctuation:String = "!") ->String{
    return "\(greeting), \(name)\(punctuation)"
}
sayHelloTo("imooc")
sayHelloTo("imooc", withGreetingWord: "hi", punctuation: "!!")

func sayHello(to name: String = "imooc", withGreetingWord greeting:String = "hello", punctuation:String = "!") ->String{
    return "\(greeting), \(name)\(punctuation)"
}
sayHello()

print("hello",1,2,3, separator: ",", terminator: ".")

//变长参数(参数的个数不确定)
func mean(numbers:Double ... ) ->Double{
    var sum:Double = 0
    //将变长参数当作一个数组
    for number in numbers{
        sum += number
    }
    return sum / Double(numbers.count)
}
mean(2)
mean(2,3)
mean(3,4,55,66)

常量参数,变量参数,inout参数

func toBinary(var num: Int) -> String{
    var res = ""
    repeat{
         res = String(num%2) + res
         num /= 2
    }while num != 0
    return res
}
toBinary(12)
var x = 100
toBinary(x)
x

//这样写没有进行交换
func swapTwoInts(var a:Int, var _ b:Int){
    let t:Int = a
    a = b
    b = t
}
var m:Int = 1
var n:Int = 2
swapTwoInts(m, n)
m
n
//这样写就可以交换
func swapTwoInts2(inout a:Int, inout _ b:Int){
    let t:Int = a
    a = b
    b = t
}
var s:Int = 1
var t:Int = 2
swapTwoInts2(&s, &t)
s
t

func initArray(inout arr: [Int], by value:Int){
    for i in 0..<arr.count{
        arr[i] = value
    }
}
var arr = [1,2,3,4,5]
initArray(&arr, by: 0)
arr

使用函数类型

func add(a:Int, _ b:Int) ->Int{
    return a+b
}
let anotherAdd:(Int,Int)->Int = add
anotherAdd(3,4)

func sayHelloTo(name:String){
    print("hello,\(name)")
}
let anotherSayHelloTo: String ->Void = sayHelloTo
anotherSayHelloTo

func sayHello(){
    print("hello")
}
let anotherSayHello1: ()->() = sayHello
let anotherSayHello2: ()->Void = sayHello
let anotherSayHello3: Void->() = sayHello
let anotherSayHello4: Void->Void = sayHello
//函数作为参数传入另一个函数
var arr:[Int] = []
for _ in 0..<100{
    arr.append(random()%1000)
}
arr
arr.sort()
arr
arr.sortInPlace()
arr
//自定义的排序
func biggerNumberFirst(a:Int, _ b :Int) -> Bool{
//    if a>b{
//        return true
//    }
//    return false
    return a > b
}
arr.sort(biggerNumberFirst)

func cmpByNumberString(a:Int, _ b:Int) -> Bool{
    return String(a) < String(b)
}
arr.sort(cmpByNumberString)

func near500(a:Int, _ b:Int) -> Bool{
    return abs(a-500) < abs(b-500) ? true:false
}
arr.sort(near500)

函数式的编程

func changeScore1(inout scores:[Int]){
    for (index,score) in scores.enumerate(){
        scores[index] = Int(sqrt(Double(score))*10)
    }
}

func changeScore2(inout scores:[Int]){
    for (index,score) in scores.enumerate(){
        scores[index] = Int(Double(score) / 150.0 * 100.0)
    }
}

var score1 = [36,61,78,89,99]
changeScore1(&score1)
var score2 = [88,101,124,137,150]
changeScore2(&score2)

*变成下面的

func changeScores(inout scores: [Int] , by changeScore:(Int) ->Int){
    for (index,score) in scores.enumerate(){
        scores[index] = changeScore(score)
    }
}
func changeScore1(score:Int) ->Int{
    return Int(sqrt(Double(score))*10)
}
func changeScore2(score:Int) ->Int{
    return Int(Double(score) / 150.0 * 100.0)
}
var score1 = [36,61,78,89,99]
changeScores(&score1, by: changeScore1)
var score2 = [88,101,124,137,150]
changeScores(&score2, by: changeScore2)

//map
var scores = [65,91,45,97,87,72,33]
//changeScores(&scores, by: changeScore1)

scores.map(changeScore1)

func isPassOrFaill(score:Int) ->String{
    return score < 60 ? "Fail" : "Pass"
}
scores.map(isPassOrFaill)
//filter
func fail(score:Int) -> Bool{
    return score<60
}
scores.filter(fail)
//reduce
func add(num1:Int, _ num2:Int) ->Int{
    return num1 + num2
}
scores.reduce(0, combine: add)
scores.reduce(0, combine: +)

func concatenate(str:String , num: Int) ->String{
    return str + String(num) + " "
}
scores.reduce("", combine: concatenate)

返回函数类型和函数嵌套

func tier1MailFeeByWeight(weight:Int) -> Int{
    return 1*weight
}
func tier2MailFeeByWeight(weight:Int) -> Int{
    return 3*weight
}
//func chooseMailFeeCalculationByWeight(weight:Int) -> (Int) -> Int{
//    return weight <= 10 ? tier1MailFeeByWeight : tier2MailFeeByWeight
//}
//func feeByUnitPrice(price:Int, weight:Int) ->Int{
//    let mailFeeByWeight = chooseMailFeeCalculationByWeight(weight)
//    return mailFeeByWeight(weight) + price * weight
//}

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

推荐阅读更多精彩内容

  • 本章将会介绍 控制流For-In 循环While 循环If 条件语句Switch 语句控制转移语句 continu...
    寒桥阅读 710评论 0 0
  • 函数是用来完成特定任务的独立的代码块。给一个函数起一个合适的名字,用来标识函数做什么,并且当函数需要执行的时候,这...
    穷人家的孩纸阅读 804评论 2 1
  • 函数是执行特定任务的代码自包含块。给定一个函数名称标识, 当执行其任务时就可以用这个标识来进行”调用”。 Swif...
    透支未来阅读 227评论 0 1
  • [The Swift Programming Language 中文版]本页包含内容: 函数是用来完成特定任务的独...
    风林山火阅读 470评论 0 0
  • 夜越黑,月却明。
    ChanningQ阅读 146评论 0 0