SwiftUI-Day5 函数

吐槽

Xcode升级,什么appdelegate都没有了,现在全是swiftUI。。。
下面的代码是playground的代码,不是swiftUI View。
参考资料:https://www.hackingwithswift.com/100/swiftui/5
时间:09 October, 2020

结果

运行快捷键:shift+command+回车
删除当前行:option+D

无参函数

func printHelp() {
    let message = """
Welcome to MyApp!
"""
    print(message)
}
printHelp()

带参数的函数

func square(number: Int) {
    print(number * number)
}
square(number: 8)

有返回值的函数

func square(number: Int) -> Int {
    return number * number
}
let result = square(number: 8)
print(result)

参数标签

to name: to是在函数外面的名字,name是函数内部的名字,牛皮。。

func sayHello(to name: String) {
    print("Hello, \(name)!")
}
sayHello(to: "Taylor")

省略参数标签

func greet(_ person: String) {
    print("Hello, \(person)!")
}
greet("Taylor")

默认参数

func greet(_ person: String, nicely: Bool = true) {
    if nicely == true {
        print("Hello, \(person)!")
    } else {
        print("Oh no, it's \(person) again...")
    }
}
greet("Taylor")
greet("Taylor", nicely: false)

多态 - Variadic Functions

func square(numbers: Int...) {
    for number in numbers {
        print("\(number) squared is \(number * number)")
    }
    print(numbers[3])//访问单个元素
}

square(numbers: 1, 2, 3, 4, 5)

抛出异常

enum PasswordError: Error {
    case obvious
}

func checkPassword(_ password: String) throws -> Bool {
    if password == "password" {
        throw PasswordError.obvious
    }

    return true
}

如果这样写,并且抛出异常,password is good 永远都不会执行。

do {
    try checkPassword("password")
    print("That password is good!")
} catch {
    print("You can't use that password.")
}

inout 参数

inout类型实现指针的功能,厉害了

func doubleInPlace(number: inout Int) {
    number *= 2
}

var myNum = 10 
doubleInPlace(number: &myNum)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值