-1

I am using pubnub sdk for socket stuff. My problem is I want to send the data dictionary format with type any but while I am trying to do so the compiler is saying like: Value of protocol type 'Any' cannot conform to 'JSONCodable'; only struct/enum/class types can conform to protocols. If I am sending with same type data then it is allowing. So how can send the data in dictionary with type Any.

var params = [String : Any]()
    
params["isContinous"] = true
params["pressure"] = 1
params["reset"] = true

params["StrokeWidth"] = 11.0

pubnub.publish(channel: "ch:broadcastPoints", message: params) { result in
    switch result {
    case let .success(response):
    print("Successful Publish Response: \(response)")
    case let .failure(error):
    print("Failed Publish Response: \(error.localizedDescription)")
    }
}
  • have you tried `[String: AnyObject]`? – Scriptable Sep 24 '21 at 08:59
  • no.............let me check –  Sep 24 '21 at 09:00
  • by using AnyObjetct it also throwning error as AnyObject' cannot be used as a type conforming to protocol 'JSONCodable' because 'JSONCodable' has static requirements –  Sep 24 '21 at 09:02
  • Create a struct which conforms to `JSONCodable`: `struct Custom: JSONCodable { let isContinous: Bool; let pressure: Int; let reset: Bool; let StrokeWidth: Double }` and use that one. `let params = Custom(isContinous: true, pressure: 1, reset: true, strokeWidth: 11.0)`. – Larme Sep 24 '21 at 09:04
  • or maybe try `[String: JSONCodable]` – Scriptable Sep 24 '21 at 09:17

1 Answers1

1

Publishing Message Using PubNub Swift SDK

Here are some code samples of how you can publish a message: https://www.pubnub.com/docs/sdks/swift/api-reference/publish-and-subscribe#publish-a-dictionary-object

If you're trying to do [String: Any], then you won’t be able to do that directly. You could pass that into our AnyJSON object, like: AnyJSON(yourDictionary)

But you should really be using custom objects instead of Any, so that you can rely on type safety.

Craig Conover
  • 4,710
  • 34
  • 59