How to parse array from description in Swift 4?

时间:2017-12-18 07:24:46

标签: ios arrays json swift parsing

I'm learning Swift 4, and I have an algorithm that output the base 64 description of an array, like that:

extension String {

    func fromBase64() -> String? {
        guard let data = Data(base64Encoded: self) else {
            return nil
        }

        return String(data: data, encoding: .utf8)
    }

    func toBase64() -> String {
        return Data(self.utf8).base64EncodedString()
    }
}
let output = [1, 2, 4, 65].description.toBase64()
print(output.fromBase64()) // "[1, 2, 4, 65]"

Now, my problem is that I need the array back in an Array, and not as a String. I've looked up on the internet but I couldn't find a parsing method for this type of array (they were all talking about JSON).

2 个答案:

答案 0 :(得分:3)

You should not rely on the Cow myNewCow = this.main.add_cows(); myNewCow.setXY(uniform(0,600), uniform(0,400)); method to produce a particular predictable output, better use a JSON encoder for that purpose (example below).

Having said that, description happens to be a valid JSON array, and a JSON decoder can parse it back to an integer array:

"[1, 2, 4, 65]"

Here is a self-contained example how you can reliably encode and decode an integer array to/from a Base64 encoded string.

let output = "[1, 2, 4, 65]"
do {
    let array = try JSONDecoder().decode([Int].self, from: Data(output.utf8))
    print(array) // [1, 2, 4, 65]
} catch {
    print("Invalid input", error.localizedDescription)
}

答案 1 :(得分:0)

Here is the way you can convert your string into @Controller() array:

Int