Swift 中的函数

来源:互联网 发布:在淘宝网上开店要钱吗 编辑:程序博客网 时间:2024/06/17 13:18

想要使用函数,必须先声明后调用,Swift 中使用 func 关键字来定义函数,每个函数都有一个函数名,用于描述函数要执行的任务,有的函数也包括参数或者返回值。

函数的基本格式

 func 函数名 (参数名1 : 参数类型, 参数名1 : 参数类型) -> 返回值类型 {       函数体       return 返回值 }

无参函数有返回值

func sayHello() -> String {    return "HelloWorld"}

多参数有返回值

func sayHello(name : String, alreadyGreeted : Bool) -> String {    if alreadyGreeted {        return "Hello again \(name)"    } else {        return "Hello \(name)"    }}

无参数无返回值函数

func test1() {    print("---------");}func test2() -> Void {    print("**********")}func test3() -> () {    print("___****");}

多返回值函数

  • 使用元组类型作为函数的返回值,可以让多个值作为一个复合值返回
func count(str: String) -> (vowels: Int,consonants:Int,other:Int) {    var vowels = 0,consonants = 0,other = 0    for character in str.characters {        switch String(character).lowercased() {        case "a","e","i","o","u": //元音            vowels += 1        case "b","c","d","f","g","h","j","k","l","m","n","p","q","r","s","t","v","w","x","y","z": //辅音            consonants += 1        default:            other += 1        }    }    return (vowels,consonants,other)}//调用count(str: "qasdfghjkjhfdfg1234567")

局部参数名和外部参数名

  • 局部参数名
func someFunc(firstParam : Int,SecondParam : Int) {}someFunc(firstParam: 1, SecondParam: 2)
  • 外部参数名
func compare(num1 x : Int, num2 y : Int) -> Int {    return x > y ? x : y}compare(num1: 1, num2: 2)

默认参数值

func sayHi(message : String , name : String = "王二小") {    print("\(name),\(message)")}sayHi(message: "hello")sayHi(message: "Hi", name: "小明")

可变参数

func arithmeticMean(numbers:Double...) ->Double {    var total : Double = 0    for number in numbers {        total += number    }    return total/Double(numbers.count)}//调用arithmeticMean(numbers: 12 ,12.12, 13.4, 15.6)

In-Out (输入输出)参数

  • 一般参数仅仅是在函数内可以改变的,当这个函数只执行完毕后变量就被销毁了,如果想要通过一个函数修改参数的值,并且让这些修改在函数调用结束后仍存在,这时可以将这个参数定义为输入输出参数
func swapTwoInts(a : inout Int, b :inout Int) {    let Temp = a;    a = b    b = Temp}var num1 = 3var num2 = 4swapTwoInts(a: &num1, b: &num2)输出num1 = 4num2 = 3

嵌套函数

func calculate(opr : String) ->(Int,Int) ->Int {    func add(a : Int,b : Int) -> Int {        return a + b    }    func sub(a : Int,b : Int) -> Int {        return a - b    }    var result : (Int,Int) -> Int    switch opr {    case "+":        result = add    case "-":        result = sub    default:        result = add    }    return result}//加法let f1:(Int,Int) -> Int = calculate(opr: "+")f1(1,3)//减法let f2:(Int,Int) -> Int = calculate(opr: "-")f2(1,3)
原创粉丝点击