Is it possible to convert a JSValue into an NSNumber?

484 views Asked by At

This will show the following error: 'JSValue' is not convertible to 'NSNumber'. If it's not possible to convert, how should I go about getting the JSValue and assigning it to my NSNumber variable?

    var sentences:NSNumber = getSentences.callWithArguments([])
2

There are 2 answers

0
DarkDust On BEST ANSWER

According to the header file JSValue.h, you need to call toNumber() on your JSValue object. So it's probably:

var sentences:NSNumber = getSentences.callWithArguments([]).toNumber()
0
David Berry On

You can try:

if let sentences = getSentences.callWithArguments([]) as? NSNumber {
    // consume sentences here
}

The if let structure is probably the simplest access to it since it may not actually BE a number, If that doesn't work, you'll have to go back to JavaScriptCore and call JSValueToNumber:

let sentences = getSentences.callWithArguments([])
let nSentences = JSValueToNumber(context, sentences, nil)