title: Converting Swift Array to NSData for NSUserDefaults.StandardUserDefaults persistent storage
body: <p>I'm trying to get my head around Swift (after being relatively competent with Obj-C) by making a small app. I would like to use NSUserDefaults to persistently save a small amount of data but I am having problems.</p>
  
  <p>I initialise an empty array of tuples like this:</p>
  
  <pre><code>var costCategoryArray: [(name:String, defaultValue:Int, thisMonthsEstimate:Int, sumOfThisMonthsActuals:Int, riskFactor:Float, monthlyAverage:Float)]=[]
  </code></pre>
  
  <p>When the array has an entry, I want to save the array to NSUserDefaults with standard Swift code such as this:</p>
  
  <pre><code>NSUserDefaults.standardUserDefaults().setObject(costCategoryArray, forKey: "financialData")
  NSUserDefaults.standardUserDefaults().synchronize()
  </code></pre>
  
  <p>I get an error saying that the tuple array doesn't conform to the AnyObject class. So I tried to turn it into NSData:</p>
  
  <pre><code>var myNSData: NSData = NSKeyedArchiver.archivedDataWithRootObject(costCategoryArray)
  var myUnarchivedData: Array = NSKeyedUnarchiver.unarchiveObjectWithData(myNSData)
  </code></pre>
  
  <p>...but I get the same error during the conversion to NSData. The object being held by my array doesn't conform to AnyObject. I've also tried at each stage to make it immutable by using:</p>
  
  <pre><code>let immutableArray = costCategoryArray
  </code></pre>
  
  <p>Ive also tried creating a class instead of using tuples which I understood would make it comply with AnyObject:</p>
  
  <pre><code>class costCategory : NSObject {
      var name : String
      var defaultValue : Int
      var thisMonthsEstimate : Int
      var sumOfThisMonthsActuals : Int
      var riskFactor : Float
      var monthlyAverage : Float
  
  
      init (name:String, defaultValue:Int, thisMonthsEstimate:Int,     sumOfThisMonthsActuals:Int, riskFactor:Float, monthlyAverage:Float) {
          self.name = name
          self.defaultValue = defaultValue
          self.thisMonthsEstimate = thisMonthsEstimate
          self.sumOfThisMonthsActuals = sumOfThisMonthsActuals
          self.riskFactor = riskFactor
          self.monthlyAverage = monthlyAverage
      }
  }
  </code></pre>
  
  <p>But the new error is:</p>
  
  <p>"Property list invalid for format: 200 (property lists cannot contain objects of type 'CFType')"</p>
  
  <p>What is the problem with an array of tuples? Why can't I store an array of class objects? I feel like I need some expert advice as so far everything I try to do with Swift is pretty much incompatible...</p>
  
  <p>Thanks!</p>