Saving Array of Struct with NSKeyedArchiver and Userdefault in which object conform to NSCoding
<p>As a Protocol oriented programming concept, I have created my model with <strong>Struct</strong>.</p>

<p>I want to save <strong>Array</strong> of "<code>Struct</code>" into Userdefault. But I am having a problem in encode/decode of the array of this model.</p>

<p>Here is my <strong>model Struct</strong></p>

<pre><code>struct Room {
    let name : String
    let id : String
    let booked : Bool
}
</code></pre>

<p>Here I created a <strong>extension</strong> like this</p>

<pre><code>extension Room {


func decode() -&gt; Room? {
    let userClassObject = NSKeyedUnarchiver.unarchiveObject(withFile: RoomClass.path()) as? RoomClass
    return userClassObject?.room
}

func encode() {
    let personClassObject = RoomClass(room: self)
    NSKeyedArchiver.archiveRootObject(personClassObject, toFile: RoomClass.path())
}

class RoomClass: NSObject, NSCoding {

    var room : Room?

    init(room: Room) {
        self.room = room
        super.init()
    }

    class func path() -&gt; String {
        let documentsPath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).first
        let path = documentsPath?.appending(("/Room"))
        return path!
    }

    func encode(with aCoder: NSCoder) {
        aCoder.encode(room!.name, forKey: "name")
        aCoder.encode(room!.id, forKey: "Id")
        aCoder.encode(room!.booked, forKey: "booked")
    }

    required init?(coder aDecoder: NSCoder) {
        let _name = aDecoder.decodeObject(forKey: "name") as? String
        let _id = aDecoder.decodeObject(forKey: "Id") as? String
        let _booked = aDecoder.decodeBool(forKey: "booked")

        room = Room(name: _name!, id: _id!, booked: _booked)

        super.init()
    }
}
}
</code></pre>

<p>When I am trying to save <strong>arrRoomList</strong>(a Array of Room objects) like this</p>

<pre><code>        self.saveRooms(arrayRooms: arrRoomList)
</code></pre>

<p>I got this error</p>

<blockquote>
  <p>[_SwiftValue encodeWithCoder:]: unrecognized selector sent to instance</p>
</blockquote>

<p>I have also tried to encode each object first and then try to save them in default, then also it gives an error.</p>

<p>Can anyone please guide me how to encode/decode the array of Struct in Userdefaults in a proper way without converting it into Dictionary?</p>