How to encode Int as an optional using NSCoding : <p>I am trying to declare two properties as optionals in a custom class - a String and an Int. </p>

<p>I'm doing this in MyClass:</p>

<pre><code>var myString: String?
var myInt: Int?
</code></pre>

<p>I can decode them ok as follows:</p>

<pre><code>required init?(coder aDecoder: NSCoder) {
  myString = aDecoder.decodeObjectForKey("MyString") as? String
  myInt = aDecoder.decodeIntegerForKey("MyInt")
}
</code></pre>

<p>But encoding them gives an error on the Int line:</p>

<pre><code>func encodeWithCoder(aCoder: NSCoder) {
  aCoder.encodeInteger(myInt, forKey: "MyInt")
  aCoder.encodeObject(myString, forKey: "MyString")
}
</code></pre>

<p>The error only disappears when XCode prompts me to unwrap the Int as follows:</p>

<pre><code>  aCoder.encodeInteger(myInt!, forKey: "MyInt")
</code></pre>

<p>But that obviously results in a crash. So my question is, how can I get the Int to be treated as an optional like the String is? What am I missing?</p>
