Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'NSNumber' is not convertible to 'Int' Swift

Tags:

int

nsnumber

I am trying to do math to set the position of a shape node. It looks like this (Swift): var score: NSNumber? score = score! + 1

xcode 6 beta 5 run perfect, but xocde 6.1 not run, report 'NSnumer' is not convertible to 'Int'

like image 702
William Kane Avatar asked Sep 05 '25 03:09

William Kane


1 Answers

I realize that this is an older question, and you have probably figure this out already, but having similar issues myself recently, i figured i'd post an answer for posterity.

Swift is (as far as I know) still undergoing design changes as a programming language, and one thing I noticed is that I needed to start wrapping my int's inside the Int() function. So your example might need to look something like this:

var score: NSNumber?
score = NSNumber(integer:score!) + 1

Edit:

To try and explain why we need to do this, I believe, is because score is an NSNumber(), which can have various numeric forms. NSNumber(integer:score!) re-wraps score! as an integer specifically, allowing us to use integers against it in math equations.

like image 184
Matt Fiocca Avatar answered Sep 08 '25 01:09

Matt Fiocca