0

Apple's document says Function random returns

An NSNumber object (a random integer value)

After running these two line of code:

let expression = NSExpression(forFunction: "random", arguments: [])
let value: AnyObject = expression.expressionValueWithObject(nil, context: nil)

What I get is a number between 0 and 1, such as 0.312047983519733.


As to Function random:, the document says it returns

An NSNumber object (a random integer value between 0 and the value in the array (exclusive))

I try to use it as according to document (take a parameter which is an NSArray object containing one NSExpression object representing a number):

let expression = NSExpression(forFunction: "random:", arguments: [NSExpression(forConstantValue: 100)]) // The compiler says "Execution was interrupted, reason: signal SIGABRT"
let value: AnyObject = expression.expressionValueWithObject(nil, context: nil)

The first line even cannot pass compiling. In the console, it says "Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'random: is not a supported method.'"


I'm not sure what the problem is. I've tried all functions for init(forFunction:arguments:), all worked as described in the document except random and random:.

fujianjin6471
  • 5,168
  • 1
  • 36
  • 32
  • Looks like an Apple bug to me - when I try, it says "random: is not a supported method" –  Aug 09 '15 at 18:29
  • @MichaelL Me too, "random: is not a supported method" appears in the console. "Execution was interrupted, reason: signal SIGABRT" appears just near that line of code. – fujianjin6471 Aug 10 '15 at 02:25

1 Answers1

0

The reason this doesn't work is because there is a slight difference in the selector name between random and randomn:. Notice the n at the end of the latter.

This should work

let expression = NSExpression(forFunction: "randomn:", arguments: 
[NSExpression(forConstantValue: 100)])
let value: AnyObject = expression.expressionValueWithObject(nil, context: nil)
Justyn
  • 1,442
  • 12
  • 27