I'm trying to cast an Objective-C NSDictionary's values to 2 Swift optionals.
These values may be missing from the original NSDictionary, in which case the function can safely be called with nil arguments.
Is there a better way of doing this?
@objc
track(_ data: NSDictionary) {
// Cast NSDictionary to Swift dictionary
guard let dataDictionary = data as? [String: Any] else {
return
}
// Extract (optional) values
let value = dataDictionary["value"]
let name = dataDictionary["name"]
// Cast Objective-C optionals if possible, otherwise assign nil
let floatValue: Float? = (value as? CGFloat != nil) ? Float(value as! CGFloat) : nil
let stringName: String? = (name as? NSString != nil) ? name as! String : nil
// Function arguments:
// name: String? = nil
// value: Float? = nil
Tracker.track(name: stringName, value: floatValue)
}
question from:https://stackoverflow.com/questions/65672050/create-swift-optionals-from-cast-nsdictionary-object