How to fix 'Cannot convert value of type '

2019-08-24 22:22发布

问题:

I use a socket.io websocket to get data from my backend and I push it with an environmentObject to the View(SwiftUI) but the problem is that I can't get the data because it is of type Any

I already tried to use "guard var data = socketData else { return }" but there is this error: Initializer for conditional binding must have Optional type, not '[Any]'

import SwiftUI
import SocketIO
import Combine

let manager = SocketManager(socketURL: URL(string: "http://localhost:30000/ios")!, config: [.log(true), .compress])
let socket = manager.defaultSocket

class Socket: BindableObject {
    let didChange = PassthroughSubject<Socket,Never>()
    var days: String = "Loading..." {
        didSet {
            didChange.send(self)
        }
    }
    static let sharedInstance = Socket()
    init() {

        socket.on(clientEvent: .connect) {data, ack in
            print("socket connected")
        }
        socket.on("dailyWeather") {data, ack in
            print("just a test")
            var data = data as String //Here is the current error
            /*do {
                let decoder = JSONDecoder()
                decoder.keyDecodingStrategy = .convertFromSnakeCase
                let city = try decoder.decode(day.self, from: data)
                self.weatherData.city = city.name
            } catch {
                print(error)
            }*/
            self.days = "cur"
        }
    }


    func establishConnection() {
        socket.connect()
    }

    func closeConnection() {
        socket.disconnect()
    }
}

Error: Cannot convert value of type '[Any]' to type 'String' in coercion

回答1:

Got the solution:

var arr = data[0]
yourString: String = (arr as AnyObject).description