0

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).

1
  • 5
    You should not rely on the description method to produce a particular output. Commented Dec 18, 2017 at 7:38

2 Answers 2

3

You should not rely on the description method to produce a particular predictable output, better use a JSON encoder for that purpose (example below).

Having said that, "[1, 2, 4, 65]" happens to be a valid JSON array, and a JSON decoder can parse it back to an integer array:

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)
}

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

// Encode:
let intArray = [1, 2, 4, 65]
let output = try! JSONEncoder().encode(intArray).base64EncodedString()
print(output) // WzEsMiw0LDY1XQ==

// Decode:
let output = "WzEsMiw0LDY1XQ=="
if let data = Data(base64Encoded: output),
    let array = try? JSONDecoder().decode([Int].self, from: data) {
    print(array) // [1, 2, 4, 65]
} else {
    print("Invalid input")
}
Sign up to request clarification or add additional context in comments.

1 Comment

You should not rely on the description method to produce a particular predictable output Cleary something to highlight. Who says that in next release of iOS Apple won't change the description? For the rest, JSON, Encodable, Plist, CSV, NSCoding, it doesn't matter, it depends on the purpose of the use (share it? "crypt it"? etc.) and then to use the best solution for the use.
0

Here is the way you can convert your string into Int array:

var toString = output.fromBase64() //"[1, 2, 4, 65]"
if let str = toString {
    let chars = CharacterSet(charactersIn: ",][ ")
    let split = str.components(separatedBy: chars).filter { $0 != "" }.flatMap { Int($0)}
    print(split)  //[1, 2, 4, 65]
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.