在 AppleScript 中从列表中选择的枚举关联数组

Enum associative array with choose from list in AppleScript

在下面的示例中,我试图 say choose from list 菜单中所选水果的颜色,但我不知道如何获得与水果相关的颜色。

set fruitList to {"apple", "orange", "blueberry"}
set fruitColor to {apple:"red", orange:"orange", blueberry:"blue"}
set fruitListItem to {choose from list fruitList}
if fruitListItem is not false then
    set fruit to get fruitColor of fruitListItem
    say fruitColor
    say fruitListItem
end if

我收到错误 无法获取 {{"apple"}} 的水果颜色。 在列表中的水果上按确定后。 AD 上的 Kaydell's answer 似乎非常接近我想要的,但我不明白如何在我的示例中使用 get。例如,在 Swift 或 PHP 中,您可能会做类似 foo['bar'] 的事情。

除了 dictionary/record 问题之外还有两个主要问题。

  • 删除 choose from list fruitList 周围的大括号,否则结果是嵌套列表。
  • choose from list returns 总是一个列表——即使 multiple selections 被禁用——或者 false 如果用户按下 Cancel。您必须使用 item 1 of
  • 展平列表

AppleScript 记录的键是像变量一样的标签,而不是字符串。标签在编译时进行评估。记录不能被字符串下标。

解决方法是从键标签转换为字符串的记录创建 NSDictionary

use AppleScript version "2.5"
use framework "Foundation"
use scripting additions

set fruitList to {"apple", "orange", "blueberry"}
set fruitColors to current application's NSDictionary's dictionaryWithDictionary:{apple:"red", orange:"orange", blueberry:"blue"}
set fruitListItem to choose from list fruitList
if fruitListItem is not false then
    set fruit to item 1 of fruitListItem
    set fruitColor to (fruitColors's objectForKey:fruit) as text
    say fruitColor
    say fruitListItem
end if

这是一个嵌套字典的例子

set userNames to {"John", "Jane"}
set users to current application's NSDictionary's dictionaryWithDictionary:{John:{name:"John Smith", age:25}, Jane:{name:"Jane Smith", age:30}}
set chosenName to choose from list userNames
if chosenName is not false then
    set userName to item 1 of chosenName
    set currentUser to users's objectForKey:userName
    set userAge to (currentUser's objectForKey:"age") as integer
    say userName
    say (userAge as text)
end if