Rhi*_*non 6 applescript function handler optional-parameters
Applescript文档表示,从 Yosemite 开始,处理程序的参数可以是可选的。
从“参数规格”部分:
带标签的参数可以通过在形式参数名称后面加上 :literal 来声明默认值。这样做会使参数在调用时成为可选参数。例如,这声明了一个 make 处理程序,其 with data 参数具有默认值:
on make new theClass with data theData : missing value现在可以在不提供 with data 参数的情况下调用该处理程序;处理程序将看到数据设置为指定的默认缺失值,然后可以对其进行测试并进行适当的处理。
因此,由于需要一个带有可选参数的处理程序,我尝试创建一个。我已经做到了这一点:
set theResult to Create of me given the string:"stuff", info:"this"
on Create given info:missing value, thestring:"stuff"
if info is missing value then
set present to false
else
set present to true
end if
return {present, thestring}
end Create
Run Code Online (Sandbox Code Playgroud)
它可以编译,但给出错误“变量 thestring 未定义。”
如果我只用一个参数调用它:
set theResult to Create of me given thestring:"stuff"
Run Code Online (Sandbox Code Playgroud)
我收到错误:“创建时缺少信息参数。” 即参数毕竟不是可选的。
如何获取在 Applescript 处理程序中工作的可选参数?
为了利用可选的标记参数,处理程序定义必须为您想要可选的参数分配一个默认值。然后,当调用者不提供该标记参数时,将使用默认值。
这是一个使用用户定义标签的示例,我发现它比神奇的 AppleScript 定义标签(of、by、for 等)更清晰
SayWhat given greeting:"Hola", farewell:"Adios"
SayWhat given greeting:"Aloha"
SayWhat given farewell:"Ciao"
on SayWhat given greeting:strGreeting : "Hello", farewell:strFarewell : "Goodbye"
log "You say " & strGreeting & "; I say " & strFarewell
end SayWhat
(*You say Hola; I say Adios*)
(*You say Aloha; I say Goodbye*)
(*You say Hello; I say Ciao*)
Run Code Online (Sandbox Code Playgroud)
您必须为您的命令定义基于 SDEF 的术语才能使其工作(这反过来又意味着需要处理 XML 和脚本包,并可能造成术语冲突,等等)。它应该使 AppleScript 库更易于使用,但实际上只是浪费每个人的时间。
最简单的方法是使用普通的位置参数,并让用户传递missing value“可选”参数,您的处理程序可以检查这些参数:
set theResult to Create("stuff", "this")
set theResult to Create("stuff", missing value)
set theResult to Create(missing value, missing value)
on Create(thestring, info)
if thestring is missing value then set thestring to "stuff"
set present to info is not missing value
return {present, thestring}
end Create
Run Code Online (Sandbox Code Playgroud)
或者让您的处理程序将单个记录作为其参数,然后将其与默认属性的记录连接起来:
set theResult to Create for {thestring:"stuff", info:"this"}
set theResult to Create for {thestring:"stuff"}
set theResult to Create for {}
on Create for args
set args to args & {info:missing value, thestring:"stuff"}
set present to info is not missing value
return {present, thestring of args}
end Create
Run Code Online (Sandbox Code Playgroud)
这两种解决方案都不是理想的。但 AppleScript 中的一切不都是如此吗?
| 归档时间: |
|
| 查看次数: |
3712 次 |
| 最近记录: |