swift-函数

2017-04-10  本文已影响0人  Zz橙淞

/*
函数的定义与调用
*/
//下面例子中的函数的名字是 greet(person:) ,之所以叫这个名字,是因为这个函数用一个人的名字当做输入,并 返回向这个人问候的语句。为了完成这个任务,你需要定义一个输入参数——一个叫做 person 的 String 值,和一个包含给这个人问候语的 String 类型的返回值:
func greet(person:String) -> String{

        let greeting = "Hello," + person + "!"
        return greeting
    }
    
    var sddd:String = greet(person: "asas");
    print(greet(person: "asas"))
    
    
    func greetAgain(person: String) -> String {
        return "Hello again, " + person + "!"
    }
    print(greetAgain(person: "Anna")) // 打印 "Hello again, Anna!"
    
    //函数参数与返回值
    //无参数函数
    func sayHelloWorld() -> String {
        return "hello, world"
    }
    print(sayHelloWorld()) // 打印 "hello, world"
    
    //多参数函数
    func greets(person:String , alreadyGreeted:Bool) -> String {
    
        if alreadyGreeted {
            return greetAgain(person:person)
        }else{
        
            return greet(person: person)
        }
    }
    print(greets(person: "Tim", alreadyGreeted:true))
    // 打印 "Hello again, Tim!"

    
    //无返回值参数
    func greet2(person: String) {
        print("Hello, \(person)!")
    }
    greet2(person: "Dave") // 打印 "Hello, Dave!"
    
    //因为这个函数不需要返回值,所以这个函数的定义中没有返回箭头(->)和返回类型。
    //被调用时,一个函数的返回值可以被忽略:
    func printAndCount(string: String) -> Int {
        print(string)
        return string.characters.count
    }
    
    func printWithoutCounting(string: String) {
        
        let _ = printAndCount(string: string)
    }
    
    printAndCount(string: "hello, world")
    // 打印 "hello, world" 并且返回值 12 printWithoutCounting(string: "hello, world") // 打印 "hello, world" 但是没有返回任何值
    
    
    //多重返回值函数
    //你可以用元祖(tuple)类型让多个值作为一个符合值从函数中返回,下例中定义了一个名为 minMax(array:) 的函数,作用是在一个 Int 类型的数组中找出最小值与最大值。
    func minMax(array:[NSInteger]) -> (min: NSInteger,max: NSInteger) {
    
        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);
    }
    
    var bounds = minMax(array: [8, -6, 2, 109, 3, 71])
    print("min is \(bounds.min) and max is \(bounds.max)")
    
    //可选元祖返回类型
    func minMax2(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)
    }
    //使用可选绑定来检查 minMax(array:) 函数返回的是一个存在的元组值还是 nil :
    if let bounds = minMax2(array: [8, -6, 2, 109, 3, 71]) {
         print("min is \(bounds.min) and max is \(bounds.max)")
    }
    
    //函数参数标签和参数名称
    func someFunction(firstParameterName: Int, secondParameterName: Int) {
        // 在函数体内,firstParameterName 和 secondParameterName 代表参数中的第一个和第二个参数值
    }
    someFunction(firstParameterName: 1, secondParameterName: 2)
    
    //指定参数标签
    func someFunction2(argumentLabel parameterName: Int) {
        // 在函数体内,parameterName 代表参数值
    }
    //这个版本的 greet(person:) 函数,接收一个人的名字和他的家乡,并且返回一句问候:
    func greet3(person: String, from hometown: String) -> String {
        return "Hello \(person)!  Glad you could visit from \(hometown)."
    }
    print(greet3(person: "Bill", from: "Cupertino"))
    // 打印 "Hello Bill! Glad you could visit from Cupertino."
    
    //忽略参数标签
    //如果你不希望为某个参数添加一个标签,可以使用一个下划线( _ )来代替一个明确的参数标签。
    func someFunction3(_ firstParameterName: Int, secondParameterName: Int) {
        // 在函数体内,firstParameterName 和 secondParameterName 代表参数中的第一个和第二个参数值
    }
    someFunction3(1, secondParameterName: 2)
    
    //默认参数值
    func someFunction4(parameterWithoutDefault: Int, parameterWithDefault: Int = 12) {
        // 如果你在调用时候不传第二个参数,parameterWithDefault 会值为 12 传入到函数体中。
    }
    someFunction4(parameterWithoutDefault: 3, parameterWithDefault: 6) // parameterWithDefault = 6
    someFunction4(parameterWithoutDefault: 4) // parameterWithDefault = 12

    //可变参数:
    //一个可变参数(variadic parameter)可以接受零个或多个值。函数调用时,你可以用可变参数来指定函数参数 可以被传入不确定数量的输入值。通过在变量类型名后面加入( ... )的方式来定义可变参数。
    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))
    
    //输入输出参数,定义一个输入输出参数时,在参数定义前加 inout 关键字。一个输入输出参数有传入函数的值,这个值被函数 修改,然后被传出函数,替换原来的值。你只能传递变量给输入输出参数。你不能传入常量或者字面量,因为这些量是不能被修改的。当传入的参数作为输入输出参数时,需要在参数名前加&符,表示这个值可以被函数修改。
    //函数参数默认是常量。下例中,(_:_:)函数有两个分别叫做a和b的输入输出参数:
    func swapTwoInts(_ a: inout NSInteger, _ b: inout NSInteger) {
    
        let temporaryA = 0
        a = b
        b = temporaryA
    }
    //你可以用两个int型的变量来调用swapTwoInts(_:_:)。需要注意的是,someInt和anotherInt在传入swapTwoInts(_:_:)函数前,都加了&的前缀:
    var someInt = 3
    var anotherInt = 107
    swapTwoInts(&someInt, &anotherInt)
    print("someInt is now \(someInt), and anotherInt is now \(anotherInt)") // 打印 "someInt is now 107, and anotherInt is now 3"
    
    
    //函数类型:
    //函数类型由函数的参数类型和返回类型组成
    func addTwoInts(_ a:NSInteger,_ b:NSInteger) -> NSInteger {
    
        return a + b
    }
    
    func multiplyTwoInts(_ a: Int, _ b: Int) -> Int {
        
        return a * b
        
    }
    
    //没有参数,没有返回值的函数
    func printHelloWorld() {
    
        print("hello world")
    }
    
    //使用函数的类型
    
    var mathFunction:(NSInteger,NSInteger) -> NSInteger = addTwoInts
    
    print("Resualt: \(mathFunction(2,3))")
    
    //有相同匹配类型的不同函数可以被赋值给同一个变量,就像非函数类型的变量一样:
    
    mathFunction = multiplyTwoInts
    print("Result: \(mathFunction(2, 3))")
    // Prints "Result: 6"
    
    
    //函数类型作为参数类型
    //你可以用(Int,Int) ->Int 这样的函数类型作为另一个函数的参数类型,这样可以将函数的一部分实现留给函数的调用者来提供
    func printMathResult(_ mathFunction:(NSInteger,NSInteger) -> NSInteger , _ a:NSInteger , _ b:NSInteger) {
    
        print("resault: \(mathFunction(a,b))")
    }
    
   print(printMathResult(addTwoInts, 3, 5))

    
   //函数作为返回值类型
    //你可以用函数类型作为另一个函数的返回类型。你需要做的是在返回箭头(->)后写一个完整的函数类型。
    func stepForward(_ input:NSInteger) -> NSInteger {
    
        return input + 1
    }
    
    func stepBackword(_ input: NSInteger) -> NSInteger {
    
        return input - 1
    }
    
    func chooseStepFunction(backword: Bool) -> (NSInteger) -> NSInteger {
    
        return backword ? stepBackword : stepForward
    }
    
    var currentValue = 3
    let moveNearerZero = chooseStepFunction(backword: currentValue > 0)
    
    print(moveNearerZero)
    
    while currentValue != 0 {
        print("\(currentValue)...")
        currentValue = moveNearerZero(currentValue)
    }
    
    //嵌套函数
    //默认情况下嵌套函数是对外界不可见得,但是可以被他们的外围函数调用。一个外围函数也可以返回它的某一个嵌套函数,使得这个函数可以在其他域中被使用
    //用返回嵌套函数的方式重写 chooseStepFunction(backward:) 函数:
    func chooseStepFunctions(backword: Bool) -> (NSInteger) -> NSInteger {
    
        func stepForward(input: NSInteger) -> NSInteger {
        return input + 1
        }
        func stepBackword(input: NSInteger) -> NSInteger {
            return input - 1
        }
        
        return backword ? stepBackword : stepForward
    }
    
    var currentValue2 = -4
    let moveNearerToZero = chooseStepFunctions(backword: currentValue2 > 0)
    // moveNearerToZero now refers to the nested stepForward() function
    while currentValue2 != 0 {
        
        print("\(currentValue2)... ")
        
        currentValue2 = moveNearerToZero(currentValue2)

    }
上一篇 下一篇

猜你喜欢

热点阅读