gpt4 book ai didi

swift - 什么时候评估 Swift 函数默认参数值?

转载 作者:搜寻专家 更新时间:2023-11-01 05:50:20 25 4
gpt4 key购买 nike

如果我给一个函数参数一个不是常量的默认值(例如,函数调用的结果)是该值只计算一次(如果是,什么时候?)还是每次函数被计算叫什么?

最佳答案

来自 The Swift Programming Language, under Language Reference > Declarations > Special Kinds of Parameters :

A parameter with an equals sign (=) and an expression after its type is understood to have a default value of the given expression. The given expression is evaluated when the function is called. If the parameter is omitted when calling the function, the default value is used instead.

您可以通过将以下内容放在 playground 中来为自己演示这一点:

import Foundation

func foo(i: UInt32 = arc4random()) {
print(i)
}

foo()
foo()
foo()
foo()
foo()

这将打印五个不同的随机数(除非随机数生成器通过某种天文上不太可能的巧合生成相同的数字五次)。

它在上面引用的文档中并不明确,因此值得注意的是,当您确实在调用函数时指定参数时,默认表达式不会被计算。您也可以在 Playground 上证明这一点:

func getSomeInt() -> Int {
print("getSomeInt() was called")
return 42
}

func bar(_ i: Int = getSomeInt()) {
print(i)
}

bar(1)

当它运行时,您会看到没有打印“getSomeInt() was called”。

关于swift - 什么时候评估 Swift 函数默认参数值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38464715/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com