Swift 中的函数

想要使用函数,必须先声明后调用,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 = 3
var num2 = 4
swapTwoInts(a: &num1, b: &num2)

输出
num1 = 4
num2 = 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)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值