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()
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")
}
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]
}