Swift-6(函数)

每日一句:

不论你在什么时候开始,重要的是开始之后就不要停止。

timg.jpeg

一、函数

  • 函数是一段完成特定任务的独立代码片段
  • 在 Swift 中,每个函数都有一个由函数的参数值类型和返回值类型组成的类型

二、函数的定义与调用

  • 函数可以有多个或者一个参数,也可以定义某种类型的数据作为返回值
  • 格式
func name(param) -> returnType {
    code
}

事例:

//定义一个吃的函数
func eat() -> Void {
    print("eat")
}
//调用吃函数
eat();
//无参数函数
//同eat函数
//多参数函数
func person(name:String, age:Int, weight:Float) -> String {
    return "my name is " + name + ",my age is " + String(age) + ",my weight is " + String(weight)
}
print(person(name: "king", age: 18, weight: 90))
//无返回值函数,严格的说是有返回值的,返回值是void
func getYouLike(like:String) {
    print("I like \(like)")
}
getYouLike(like: "apple")
//多重返回值函数
func calculateYourAge(weight: Int, height: Int) -> (age:String, name:String) {
    if weight == 0 {
        return ("18", "king")
    } else {
        return ("20", "jone")
    }
}
let person = calculateYourAge(weight: 12, height: 12)
print(person)
//忽略参数,利用 _ ,  默认参数值
func personForMen(_ name:String, age:Int, weight:Float = 90.0) -> String {
    return "my name is " + name + ",my age is " + String(age) + ",my weight is " + String(weight)
}
personForMen("king", age: 18)

三、函数类型作为参数

事例:

// TODO: 函数类型作为参数
func mathYourAge(_ calculateYourAgeName:(Int,Int)->(age:String, name:String), a:Int, b:Int) {
    print(calculateYourAgeName(a, b))
}
mathYourAge(calculateYourAge, a: 10, b: 10)

四、函数类型作为返回值

事例:

// TODO: 函数作为返回值
func exchangeName(name:String) -> Bool {
    if name == "king" {
        return true
    }
    return false
}
func mathYourName(name:String) -> (String) -> Bool {
    return exchangeName(name:)
}
let change = mathYourName(name: "king")
change("king")

gitHub地址:(https://github.com/kingbroad/SwiftStudy)(欢迎👏关注❤️)

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。