1

I'd like to be able to encode a class with an array of optional values. Xcode errors with "Cannot invoke 'encode object' with an argument list of type '([SKSpriteNode?], for key: String').

 class MyCustomNode: SKNode {

     var possibleSprites:[SKSpriteNode?] = [nil, nil, nil, nil, nil, nil, nil]

 ...

 }

override func encodeWithCoder(aCoder: NSCoder) {

    aCoder.encodeObject(self.possibleSprites, forKey: "POSSIBLESPRITES")
    super.encodeWithCoder(aCoder)

}

Is this possible to achieve? If not, what are other options?


Question on proper decoding...

With the following,

 let x:[AnyObject!] = aDecoder.decodeObjectForKey("POSSIBLESPRITES") as! [AnyObject]
 self.possibleSprites = x.map { $0 == NSNull() ? nil : $0 }

I get Xcode error: “Cannot invoke 'map' with an argument list of type '((_) -> _)'”

I believe it has to do with the return type, but not sure how to solve...

1
  • 1
    How about var a:[AnyObject] = [NSNull(),NSNull()] Commented Jul 5, 2015 at 1:57

1 Answer 1

1

With Objective-C you can't encoding a nil pointer either. You need to map self.possibleSprites to an array of AnyObject? and use NSNull in place of nil.

let x : [AnyObject!] = self.possibleSprites.map { $0 == nil ? NSNull() : $0 }
aCoder.encodeObject(x, forKey: "POSSIBLESPRITES")

Just remember to decode it properly on the way back.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.