Random object of array

How would you do to get an array’s object, randomly?
is there any possibility to replace the scripting addition part with an AppleScriptObjC method?

use framework "Foundation"
use scripting additions

set anArray to current application's NSArray's arrayWithArray:{"bear", "leopard", "whale", "snake", "eagle", "kiwi", "dodo"}
anArray's objectAtIndex:(random number (anArray's |count|()) - 1)

Objective-C doesn’t have a random number method. People just generally drop down to the underlying C code to generate random numbers.

If you’re running 10.12 or later, you can use:

set theObj to anArray's shuffledArray()'s firstObject()
1 Like

@sphil

Thanks for the info.

@ShaneStanley

Not yet.
But it’s planned by the next weeks…

:wink:

If you are referring to macOS Sierra, you may want to do some research first.
There have been numerous issues with various apps reported after upgrade to Sierra. Quite a few which affect AppleScript.

I’m running macOS 10.11.6, and see no compelling reason to upgrade to Sierra. But, YMMV.

I forgot a vital line:

use framework "GameplayKit"

The -shufledArray method is in a different framework.

@ShaneStanley
Ok. It’s recorded in my “snippets for future” repository.

@JMichaelTX
I certainly won’t upgrade before being sure there’s no bugs with my work tools.
Which applications have you heard of ?
I’m particulary interested in Adobe CC and M$ Office.

I have not been tracking it closely, since I have no plans to upgrade.
Probably its best to do some searches with “sierra” & the app names of interest.
Also, “10.12”, of course.