Random object of array


(Jonas Whale) #1

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)

(Phil Stokes) #2

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

(Shane Stanley) #3

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

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

(Jonas Whale) #4


Thanks for the info.


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


(Jim Underwood) #5

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.

(Shane Stanley) #6

I forgot a vital line:

use framework "GameplayKit"

The -shufledArray method is in a different framework.

(Jonas Whale) #7

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

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.

(Jim Underwood) #8

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.