函数

作者: 心底碎片 | 来源:发表于2016-09-08 17:24 被阅读17次
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
}

相关文章

  • Excel(三)

    AND函数 OR函数 NOT函数 IF函数 频率分析函数FREQUENCY

  • if、else if、for、while、repeat函数

    ①if函数 ②else if函数 ③for函数 ④while函数 ⑤repeat函数

  • strsplit、mapply、paste、match函数

    strsplit函数 mapply函数 strsplit函数 mapply函数 paste函数 match函数 第...

  • Oracle中常用函数(SQL)

    Oracle函授有以下几个分类:数字函数、字符函数、日期函数、转换函数、集合函数、分析函数 数字函数: 字符函数:...

  • MySQL函数

    字符函数 数字运算函数 比较运算符和函数 日期时间函数 信息函数 聚合函数 加密函数 流程函数

  • BI-SQL丨AND & OR & IN

    AND函数 & OR函数 & IN函数 AND函数、OR函数和IN函数都可以理解是WHERE函数的补充,当然也可以...

  • Python之函数

    课程大纲 函数定义 函数的参数 函数的返回值 高阶函数 函数作用域 递归函数 匿名函数 内置函数 函数式编程 将函...

  • 函数基本知识

    函数 函数的定义: def 函数名() 函数的调用:函数名() #不能将函数调用放在函数定义上方 函数的文档注...

  • 积分表——不定期更新

    基本初等函数包括: 常函数: 幂函数 指数函数 对数函数 三角函数 反三角函数 I、反函数Ⅱ、复合函数:初等函数(...

  • MySQL基本使用

    函数 常用函数 数学函数 字符串函数 日期函数

网友评论

      本文标题:函数

      本文链接:https://www.haomeiwen.com/subject/vbnsettx.html