2012-12-25 63 views
3

由于熟悉编程,我缺少用三元运算符分配变量的能力(即“如果某事为真,则将该变量设置为x,否则将其设置为y”)。我在想这样的事情:AppleScript是否具有条件(三元)运算符的等效项?

set my_string to (if a is 0 return "" else return " - substring") 

这当然不起作用,我还没有找到类似的东西。有没有另一种方式来实现这个与苹果?

+0

对于它的价值,这个操作符的名称是“条件操作符”。它恰好是**三元运算符,但它不是**三元运算符,因为虽然它是目前唯一的三元运算符,但没有任何东西阻止某人发明另一个三元运算符。 – ErikE

回答

2

看起来的AppleScript不支持有条件的经营者,但你可以使用清单,用于此目的的两个元素。当然,这不是一般很优雅:

set my_string to item (((a is 0) as integer) + 1) of {"", " - substring"} 

还有另外一个选择:你可以使用shell脚本

set b to (do shell script "test " & a & " -eq 0 && echo 'is 0' || echo 'is not 0'") 

我怎能忘记? :)

在你的情况下,它会更简单(因为如果根本没有回声,将返回一个空字符串)。

set b to (do shell script "test " & a & " -eq 0 || echo '- substring'") 
2
if a is 0 then 
    set my_string to "" 
else 
    set my_string to " - substring" 
end if 

set a to 7 

set my_string to my subTern(a) 

on subTern(aLocalVar) 
    if aLocalVar is 0 then return "" 
    if aLocalVar is not 0 then return " - substring" 
end subTern