SwiftUI基础之struct如何转化为dictionary

代码

import SwiftUI
import Foundation

struct Test: Encodable {
    let name: String = "name"
    let age: Int = 10
    let height: Double = 173
}

extension Encodable {
  func asDictionary() throws -> [String: Any] {
    let data = try JSONEncoder().encode(self)
    guard let dictionary = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: Any] else {
      throw NSError()
    }
    return dictionary
  }
}
let test = Test()
print(try test.asDictionary())

更多SwiftUI教程和代码关注专栏

  • 请关注我的专栏icloudend, SwiftUI教程与源码
    https://www.jianshu.com/c/7b3e3b671970

你可能感兴趣的:(SwiftUI基础之struct如何转化为dictionary)