美文网首页
Swift 2 学习笔记 8.函数

Swift 2 学习笔记 8.函数

作者: Maserati丶 | 来源:发表于2018-11-21 20:28 被阅读0次

    课程来自慕课网liuyubobobo老师


    函数
    • 函数基础
    func sayHello(name: String?) -> String {
        return "Hello " + ( name ?? "Guest" )
    }
    
    var nickname: String? = nil
    sayHello(name: nickname)
    
    • 使用元组返回多个值
    func findMaxAndMin( numbers: [Int] ) -> ( max: Int, min: Int )? {
        if numbers.isEmpty {
            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]? = [21,123,53,122,33,252]
    scores = scores ?? nil
    if let result = findMaxAndMin(numbers: scores!) {
        print(result.max)
        print(result.min)
    }
    
    • 函数的命名
    func sayHello(to name: String, with greeting: String) -> String {
        return "\(greeting),\(name)"
    }
    
    sayHello(to: "imooc", with: "Hello")
    
    func mutiple(_ num1: Int,_ num2: Int) -> Int {
        return num1 * num2
    }
    
    mutiple(4, 2)
    
    • 默认参数值
    func sayHello(to name: String = "Playground", with greeting: String = "Hello") -> String {
        return "\(greeting),\(name)"
    }
    
    sayHello(to: "imooc", with: "Hi")  // Hi,imooc
    sayHello(to: "bobobo")  // Hello,bobobo
    sayHello()// Hello,Playground
    
    • 可变参数
    func mean(_ numbers:Double ...) -> Double {
        var sum:Double = 0
        // 将变长参数当做一个数组看待
        for number in numbers {
            sum += number
        }
        return sum/Double(numbers.count)
    }
    
    mean(2)  // 2
    mean(2,3)  // 2.5
    mean(2,3,41,5,1,23,4,52)  // 16.375
    
    
    func sayHello(to names: String ... , with greeting: String = "Hello") {
        for name in names {
            print("\(greeting),\(name)")
        }
    }
    
    sayHello(to: "A","B","C", with: "Hi")
    
    • 常量参数、变量参数和inout参数 -> Swift3
    // 变量参数不再使用
    // inout关键字写在参数后面
    // 交换两个整型
    func swapTwoInts(_ a: inout Int , _ b : inout Int) {
        (a,b) = (b,a)
    }
    var numA: Int = 3
    var numB: Int = 4
    swapTwoInts(&numA, &numB)
    numA  // 4
    numB  // 3
    
    // 将一个整型数组每一个元素都初始化成0
    func initArray(arr: inout [Int], by value:Int ) {
        for i in 0..<arr.count {
            arr[i] = value
        }
    }
    var arr = [1,2,3]
    initArray(arr: &arr, by: 0)
    arr  // [0,0,0]
    
    • 函数类型
    // 产生一个随机数组
    var arr: [Int] = []
    for _ in 0..<100 {
        arr.append(Int(arc4random()%1000))
    }
    // 按从大到小排序
    func biggerNumberFirst (a: Int , b: Int) -> Bool {
        return a > b
    }
    arr.sort(by: biggerNumberFirst)
    // 按最接近500排序
    func near500 (a: Int, b: Int) -> Bool {
        return abs(a-500) < abs(b-500) ? true : false
    }
    arr.sort(by: near500)
    
    • 函数式编程初步
    func changeScores ( scores: inout [Int], by changeScore:(Int) -> Int ) {
        for (index,score) in scores.enumerated() {
            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 scores1 = [67,72,45,96,80]
    changeScores(scores: &scores1, by: changeScore1)
    
    var scores2 = [123,78,96,102,88]
    changeScores(scores: &scores2, by: changeScore2)
    
    
    //map
    var scores = [67,72,45,96,80]
    scores.map(changeScore1)  // [81, 84, 67, 97, 89]
    scores  // [67,72,45,96,80]
    
    //filter
    func fail(score: Int) -> Bool {
        return score < 60
    }
    scores.filter(fail)  // [45]
    scores  // [67,72,45,96,80]
    
    //reduce
    func add(num1: Int, num2: Int ) -> Int {
        return num1 + num2
    }
    scores.reduce(0, add)  // 360
    scores.reduce(0, +)  // 360
    
    • 返回函数类型和函数嵌套
    // 两种邮费计算方法
    func tier1MailFee(by weight: Int) -> Int {
        return 1 * weight
    }
    
    func tier2MailFee(by weight: Int) -> Int {
        return 3 * weight
    }
    // 计算商品总花费(邮费+商品价格)
    func fee(price: Int, weight: Int) -> Int {
        // 嵌套选择邮费计算方法的函数
        func chooseMailFeeCalculation(by weight: Int) -> (Int) -> Int {
            return weight <= 10 ? tier1MailFee : tier2MailFee
        }
        
        let mailFeeByWeight = chooseMailFeeCalculation(by: weight)
        return mailFeeByWeight(weight) + price
    }
    
    fee(price: 100, weight: 10)  // 110
    fee(price: 100, weight: 20)  // 160
    

    相关文章

      网友评论

          本文标题:Swift 2 学习笔记 8.函数

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