【问题标题】:To unwrap the CBOR decoded Data in Swift在 Swift 中解开 CBOR 解码的数据
【发布时间】:2020-06-23 18:35:48
【问题描述】:

我在 Swift 中有以下结构

struct SerializableRequest {        
  var r: Int
  var m: String
  var d: String
  var b: [UInt8]
}

然后我创建一个结构的实例:

SerializableRequest(r: 1, m: "c", d:"l", b: [42, 24] ) 

并使用 CBOR 对其进行编码,得到:[164, 97, 109, 97, 99, 97, 98, 66, 42, 24, 97, 100, 97, 108, 97, 114, 1]

现在我想使用上面的字节数组再次将其解码回 Struct,但在解码时会产生输出

([SwiftCBOR.CBOR.utf8String("d"): SwiftCBOR.CBOR.utf8String("l"), 
  SwiftCBOR.CBOR.utf8String("r"): SwiftCBOR.CBOR.unsignedInt(1), 
  SwiftCBOR.CBOR.utf8String("b"): SwiftCBOR.CBOR.byteString([42, 24]), 
  SwiftCBOR.CBOR.utf8String("m"): SwiftCBOR.CBOR.utf8String("c")]
)

如何使用 https://github.com/myfreeweb/SwiftCBOR 使用 PATTERN MATCHING 获得 Struct

【问题讨论】:

    标签: ios swift bluetooth cbor


    【解决方案1】:

    我已经阅读了 SwiftCBOR 文档,我想你可以这样使用它:

    struct SerializableRequest {
        var r: Int
        var m: String
        var d: String
        var b: [UInt8]
    
        init(cborArr: [CBOR]) {
    
            for (i, val) in cborArr.enumerated() {
                if i == 0 {
                   //
                } else if i == 1 {
                    if case let CBOR.utf8String(string) = val {
                        m = string
                    }
                } else if (i == 2) {
                    // and so on
                }
            }
        }
    }
    

    正如你在上面看到的,我知道在第一个位置有一个字符串,所以我通过 cborArr 进行枚举,检查每个项目的位置并尝试解码值(因为我希望第一个位置是字符串) .另外,你可以使用 CodableCBORDecoder,check this out

    【讨论】:

      【解决方案2】:

      试试这个简单的例子

      import Foundation
      import SwiftCBOR
      
      struct S: Codable {
          let integer: Int
          let string: String
          let byteArray: [UInt8]
      }
      
      let s1 = S(integer: 1, string: "Hello, World", byteArray: [1,2,255])
      
      
      do {
          let encoder = CodableCBOREncoder()
          // encoded Data
          let data = try encoder.encode(s1)
          
          let decoder = CodableCBORDecoder()
          // decoded S
          let s2 = try decoder.decode(S.self, from: data)
          
          print(s2)
          // S(integer: 1, string: "Hello, World", byteArray: [1, 2, 255])
      
          
      } catch {
          print(error)
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-11-12
        • 2019-05-23
        • 2018-10-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多