简体   繁体   中英

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

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

I solved it like that:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM