core data - Array of NSManagedObjects and reduce function compile but fail at runtime -


using playground simulate problem core data based app turned issue can't seem understand.

class pole { var length: nsnumber! }   var poles: [pole] = []   let pole1 = pole() pole1.length = 1 poles.append(pole1) let pole2 = pole() pole2.length = 2 poles.append(pole2) var sum = poles.reduce(0) { $0 + $1.length } // error not find member 'length' 

the property (attribute) named length nsnumber in nsmanagedobject class (entity).

changing type nsnumber! int! allows line compile , run correctly in playground.

leaving the type nsnumber! , changing the offending line follows:

var sum = poles.reduce(0) { $0 + int($1.length) }  

also compiles , run correctly in playground. next step, taking app, using actual nsmanagedobject entity , attribute compiles fails @ runtime. failure 'unwrapping nil'.

so bottom line can't figure out how use reduce function when attribute nsnumber , casting int doesn't seem acceptable.

nsnumber foundation class used wrap numbers otherwise represented in value type, can used wherever reference type expected. swift bridges integer literals nsnumber, not other way around, original reduce closure trying add integer literal nsnumber, getting confused, , giving weird error message.

creating new int 1 way handle problem:

var sum = poles.reduce(0) { $0 + int($1.length) } 

or can use nsnumber's integervalue property, returns instance's value int:

var sum = poles.reduce(0) { $0 + $1.length.integervalue } 

Comments

Popular posts from this blog

ruby on rails - RuntimeError: Circular dependency detected while autoloading constant - ActiveAdmin.register Role -

c++ - OpenMP unpredictable overhead -

javascript - Wordpress slider, not displayed 100% width -