1

I have to serialize an array like PHP does. This is the PHP line of code I have to translate in Swift 4:

serialize(array('p'=>2,'m'=>10,'e'=>20))

I just converted the php array in a Swift struct:

struct codeStructure: Codable {
var p: Int
var m: Int
var e: Int

init() {
    p = 2
    m = 10
    e = 20
   }
}

but I need a serialize() function that returns a string like:

a:3:{s:1:"p";i:2;s:1:"m";i:10;s:1:"e";i:20;}

Any hints? Thank you in advance.

Michele

iMichele
  • 51
  • 7
  • 1
    Can I ask why you have to do it the same as PHP? (out of curiosity) – Scriptable Jun 28 '18 at 13:02
  • Which is your goal? Maybe exist a better solution. – Lito Jun 28 '18 at 13:19
  • There is no such function in Swift, you'd have to implement it yourself. Consider to use a more common interchange format, such as JSON. – Martin R Jun 28 '18 at 13:20
  • Your solution https://stackoverflow.com/a/44551842/2342915, you should use the codable protocol for that – Lito Jun 28 '18 at 13:22
  • I have to communicate with a server that accepts in the header a value "PHP serialized" and then base64encoded and I'm unable to modify the server side code... – iMichele Jun 28 '18 at 13:51
  • like Martin R said, you will need to implement it yourself unless there is an existing third party library that you could use. – Scriptable Jun 28 '18 at 13:54

1 Answers1

0

You can serialize the object to json and then convert it. I guess it will be much easier than convert object to php serialize.

Kryštof Matěj
  • 462
  • 3
  • 16