Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
321 views
in Technique[技术] by (71.8m points)

objective c - Create Swift optionals from cast NSDictionary object

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Firstly

let stringName: String? = (name as? NSString != nil) ? name as! String : nil

Can be simplified as

let stringName: String? = name as? String

But if we want to make the modification earlier, we can avoid the [String: Any] from the start:

let floatValue = (data["value"] as? NSNumber)?.floatValue
let nameValue = data["name"] as? String

If data["value"] doesn't exist, it will be nil. If it's not a NSNumber (since it's the Objective-C basic way to encapsulate Float into a Object) it will be nil. In the end, the floatValue will be nil or have the real value.

Same logic for the nameValue.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...