Home > database >  Swift - Cannot convert value of type 'Any?' to expected argument type 'String'
Swift - Cannot convert value of type 'Any?' to expected argument type 'String'

Time:08-20

if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] {
    
    if let nickn = json["nickname"] as? String {
        if(nickname != nickn){
            nickname = nickn
        }
    }
    
    var serverScalingString = ""
    serverScalingString  = "0,"   json["srvFile0"] as? String   "|"
    
    serverScaling = serverScalingString
    
}

I get "Cannot convert value of type 'Any?' to expected argument type 'String'" on

serverScalingString  = "0,"   json["srvFile0"] as? String   "|"

I don't need any null safety on the string json["srvFile0"], if this would be null then the app can just crash

changing as? to as! doesn't work

Please help

CodePudding user response:

If it is ok to crash

let temp = json["srvFile0"]! as! String 

But much better would be to avoid that

if let temp = json["srvFile0"], let serverFile = temp as? String {

CodePudding user response:

I solved it like that:

serverScalingString  = "0,"   (json["srvFile0"] as? String ?? "")   "|"
  • Related