How to parse array from description in Swift 4?

前端 未结 2 901
一生所求
一生所求 2021-01-26 13:05

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


        
相关标签:
2条回答
  • 2021-01-26 13:25

    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")
    }
    
    0 讨论(0)
  • 2021-01-26 13:33

    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]
    }
    
    0 讨论(0)
提交回复
热议问题