Swift笔记:函数

函数

//声明函数
func sayhello(person:String) -> String {
    let  str = "hello," + person

    return str
}

//调用函数
print(sayhello("locay"))

//hello,locay

以 func 作为前缀。 ->(一个连字符后跟一个右尖括号)后跟返回类型的名称的方式来表示函数返回值。函数名后面()为函数参数。

无参函数(Functions Without Parameters)

func sayHelloWorld() -> String {
    return "hello, world"
}
print(sayHelloWorld())
// prints "hello, world"

多参数函数 (Functions With Multiple Parameters)

func sayHello(personName: String, alreadyGreeted: Bool) -> String {
    if alreadyGreeted {
        return sayHelloAgain(personName)
    } else {
        return sayHello(personName)
    }
}
print(sayHello("Tim", alreadyGreeted: true))
// prints "Hello again, Tim!"

无返回值函数(Functions Without Return Values)

func sayGoodbye(personName: String) {
    print("Goodbye, \(personName)!")
}
sayGoodbye("Dave")
// prints "Goodbye, Dave!"

多重返回值函数(Functions with Multiple Return Values)

func minMax(array: [Int]) -> (min: Int, max: Int) {
    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)
}

函数类型(Function Types)

每个函数都有种特定的函数类型,由函数的参数类型和返回类型组成。

func addTwoInts(a: Int, _ b: Int) -> Int {
    return a + b
}
func multiplyTwoInts(a: Int, _ b: Int) -> Int {
    return a * b
}

这两个函数的类型是 (Int, Int) -> Int,可以解读为“这个函数类型有两个 Int 型的参数并返回一个 Int 型的值。”。

func printHelloWorld() {
    print("hello, world")
}

这个函数的类型是:() -> Void,或者叫“没有参数,并返回 Void 类型的函数”。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值