PGDev
PGDev

Reputation: 24341

Archiving and Unarchiving in Swift 3.0

I have some problems regarding archiving and unarchiving data in swift 3.0.

I read some posts about the same but still don't have complete clarity about some cases.

  1. enum (I used rawValue to archive it.)

  2. struct (I read about the extension method to archive it in http://swiftandpainless.com/nscoding-and-swift-structs/). Is there any other way to do it?

  3. Array

Since array is also a struct, so it must also follow the archiving convention same as of a struct. But I am able to archive an array of basic data types eg. String, Int etc. directly. i.e.

let arr = ["1", "2"], is archived directly without any extension.

Also, how does it work in an array of custom objects?

  1. Set

  2. Dictionary

Upvotes: 0

Views: 606

Answers (1)

Martin
Martin

Reputation: 155

I had the same issue and found this solution for my struct:

struct Series {

var name: String?
var season: String?
var episode: String?

init(name: String?, season: String?, episode: String?) {
    self.name = name
    self.season = season
    self.episode = episode
}

static func archive(w: Series) -> Data {
    var fw = w
    return Data(bytes: &fw, count: MemoryLayout<Series>.stride)
}

static func unarchive(d: Data) -> Series {
    guard d.count == MemoryLayout<Series>.stride else {
        fatalError("Error!")
    }

    var w: Series?
    d.withUnsafeBytes({(bytes: UnsafePointer<Series>) -> Void in
        w = UnsafePointer<Series>(bytes).pointee
    })
    return w!
}

}

I can call the archiver like this:

var series = [Series]()
let arcData = Series.archive(w: series[0])

and the unarchiver like this:

var seriesItems = [Data]()
let unarcData = [Series.unarchive(d: seriesItems[0])]

But when I enter a name with a space the app crashes. I don't no why, because in case of season and episode there are also spaces like in "Season 1".

Upvotes: 0

Related Questions