首页 > 解决方案 > AppleScript:IF 命令不执行

问题描述

我是 AppleScript 的初学者,所以我真的不太了解。我一直在尝试让用户从一系列情况中进行选择,然后根据他们的选择做出适当的回应。但是,我遇到了一些问题:

  1. 脚本运行但不显示通知。
  2. 有没有比仅仅链接很多 IF 语句更好的方法?

PS:我离完成整个剧本还差得很远。

on run
    choose from list {"Thunderstorm", "Flood", "Heatwave", "Hazmat"} with prompt "Please select one of the emergency situations below" without multiple selections allowed and empty selection allowed
    return the result as string
    if string is Thunderstorm then display notification "hello"
end run

标签: if-statementapplescript

解决方案


你对你正在查看的示例代码做了一些很好的猜测;但其中一些猜测是错误的。随着时间的推移,您会更好地了解 AppleScript 的工作原理。

  1. choose from list通过用引号将其文本括起来,您可以将情境名称正确地输入为行中的字符串。但是在检查它是否是雷暴时,不要用引号括住该文本。AppleScript 正在查看一个调用Thunderstorm其内容的变量,而不是查看文本字符串“Thunderstorm”。

  2. return the result as string不会创建变量调用string,而是结束处理程序调用run,返回the result到任何代码调用run,作为文本字符串。要将 的结果分配给choose from list变量,请使用类似set theSituation to the result as string.

这是您的代码如何更好地工作的示例:

on run
    --get the situation we're dealing with
    choose from list {"Thunderstorm", "Flood", "Heatwave", "Hazmat"} with prompt "Please select one of the emergency situations below" without multiple selections allowed and empty selection allowed
    copy the result as string to theSituation

    --Thunderstorms require that the user be immediately notified
    if theSituation is "Thunderstorm" then display notification "hello"
end run

由于您将其用作run处理程序,因此您可能不想返回任何结果,因为您很少调用运行处理程序。但是,如果您确实需要返回结果,则处理程序的最后一行(就在 之前end run)将是:

return theSituation

您可能会四处寻找适合您需要的 AppleScript 教程。Apple 有他们的 AppleScript 语言指南简介

可以使用 if/else if/else if 链接 IF 语句:

on run
    --get the situation we're dealing with
    choose from list {"Thunderstorm", "Flood", "Heatwave", "Hazmat"} with prompt "Please select one of the emergency situations below" without multiple selections allowed and empty selection allowed
    copy the result as string to theSituation

    --Thunderstorms require that the user be immediately notified
    if theSituation is "Thunderstorm" then
        display notification "hello"
    else if theSituation is "Flood" then
        display notification "hike pants"
    else if theSituation is "Heatwave" then
        display notification "Play Bing Crosby"
    else if theSituation is "Hazmat" then
        display notification "Use highway 183"
    end if
end run

AppleScript 中没有 switch/case 控制结构。


推荐阅读