0

How can I save custom object array to NSUserDefauls like:

class Settings: NSObject {
   var name: String? = ""
   var addresss: [Address] = [Address]()
   var addressSelectedIndex: Int = 0
   ....
}

class Address: NSObject {
   var street: String? = ""
   var city: String? = ""
   ....
}

I have added encoder and decoder to the both classes. Getting error at:

func encodeWithCoder(aCoder: NSCoder) {
   ....
   if let _addresss = self.addresss { // here
      aCoder.encodeObject(_ addresss, forKey: "addresss")
   }
}

Initializer for conditional binding must have Optional type, not '[Address]'

rmaddy
  • 314,917
  • 42
  • 532
  • 579
alrarea
  • 110
  • 1
  • 9
  • 3
    You don't need to use if let address = self.address, directly use `aCode.encodeObject(address, forKey: "address")` is fine. **if let** only works for checking optional type, but your definition of address is not optional type. – bubuxu Jan 01 '17 at 13:11
  • Your question has nothing to do with saving custom objects in `NSUserDefaults`. It's about the Swift error. Please [search on the error](http://stackoverflow.com/search?q=%5Bswift%5D+Initializer+for+conditional+binding+must+have+Optional+type%2C+not) before posting your question. – rmaddy Jan 01 '17 at 16:45
  • thanks bubuxu, it worked – alrarea Jan 02 '17 at 05:57

2 Answers2

0

Since you declared

var addresss: [Address] = [Address]()

addresss is not optional, therefore you don't need to use the if let.

You should declare it as:

var addresss: [Address]?
dirtydanee
  • 6,081
  • 2
  • 27
  • 43
Giordano Scalzo
  • 6,312
  • 3
  • 31
  • 31
0

addresss is not an optional property, you initialise it to be an empty array. Therefore it makes no sense to do nil check on this property using if let.

Your encode function should look the following:

func encodeWithCoder(aCoder: NSCoder) {
   ....
   aCoder.encodeObject(addresss, forKey: "addresss")
}
dirtydanee
  • 6,081
  • 2
  • 27
  • 43