Search code examples
applescript

getting an index of a selected item in a list apple script


I'm trying to write an apple script with a large list and I want to prompt the user to select an item from the list and then the script should display an index of this item. Getting the script to prompt the user to select from list wasn't a problem, but I can't get an index of a selected list item.

Here is the example code and a loop I tried so far

set cities to {"New York", "Portland", "Los Angelles", "San Francisco", "Sacramento", "Honolulu", "Jefferson City", "Olimpia"}
set city_chooser to choose from list cities
set item_number to 0
repeat with i from 1 to number of items in cities
    set item_number to item_number + 1
    if i = city_chooser then
        exit repeat
    end if
end repeat
display dialog item_number

It just gives me the number of items in the list.


Solution

  • Vanilla AppleScript does not provide an indexOfObject API. There are three ways:

    1. An index based loop which iterates the list and returns the index when the object was found.
    2. Bridging the list to AppleScriptObjC to use the indexOfObject API of NSArray.
    3. If the list is sorted a binary search algorithm which is very fast.

    A fourth way is to populate the list with this format

    1 Foo
    2 Bar
    3 Baz
    

    and get the index by the numeric prefix but this is quite cumbersome for large lists.


    Edit:

    There are a few issues in the code. The main two are that choose from list returns a list (or false) and you are comparing a string with the index variable, an integer.

    Try this

    set cities to {"New York", "Portland", "Los Angeles", "San Francisco", "Sacramento", "Honolulu", "Jefferson City", "Olympia"}
    set city_chooser to choose from list cities
    if city_chooser is false then return
    set city_chooser to item 1 of city_chooser
    repeat with i from 1 to (count cities)
        set city to item i of cities
        if city = city_chooser then exit repeat
    end repeat
    display dialog i