How to add a city to the list and create a corresponding if-then string

applescript

My current code:

property cityList : {"City A","City B","City C","New City"}
choose from list cityList with prompt "Choose your city:"
set choice to result
if choice is not false then set city to choice
if choice is false then error number -128

if (city as string) is "City A" then
    set lat to 1
    set lon to 1
else if (city as string) is "City B" then
    set lat to 1
    set lon to 1
else if (city as string) is "City C" then
    set lat to 1
    set lon to 1
else if (city as string) is "New City" then
    set lat to my customLat()
    set lon to my customLon()
    set city to my customCity()
    set x to the length of cityList
    set the end of cityList to "New City"
    copy city as string to item x of cityList
end if

--script that does things based on values of lat and lon

where customLat() is a subroutine that prompts the user for a latitude, tries to coerce it to a number and outputs an error if it can't, and outputs another error if said number is not between -90 and 90, and customLon() is a similar one, but it tests for between -180 and 180 instead. In either case, if an error is returned, it prompts the user for the relevant number once more. customCity() merely prompts the user for the city's name.

My problem is what to type in after the copy city line. Is there a way to add an if block in my code – that is, have the code write on top of itself – based on the result of the "New City" if block? That is, once the code has established the variables city, lat, and lon, it will then insert before the end if line a similar block to the previous cities:

else if (city as string) is "Newly Inputted City" then
    set lat to 1
    set lon to 1

I am looking for a way that the user can input a custom city and coordinates, and the code will overwrite itself to allow that as a valid option, so that the next time the script is run the custom city will be available as an option, and selecting it will automatically set its lat and lon, just like the other cities.

Best Answer

Your code doesn’t need to rewrite itself. else already takes care of all cases that are unaccounted for:

property cityList : {"City A", "City B", "City C", "New City"}
set choice to choose from list cityList with prompt "Choose your city:"
if choice is false then
    error number -128
end if

set city to choice as string
if city is "New City" then
    set lat to my customLat()
    set lon to my customLon()
    set city to my customCity()
    set x to the length of cityList
    set the end of cityList to "New City"
    copy city to item x of cityList
else
    set lat to 1
    set lon to 1
end if