I am trying to convert a value stored in a Dictionary to a CGFloat
let dict:Dictionary <String, Any> = ["num": 100]
let cgf = CGFloat(d["num"] as Double)
let view = UIView()
view.frame = CGRectMake(cgf,200,10,10)
This causes a run time error:
Thread 1: EXC_BREAKPOINT (code=EXC_I386_BPT, subcode=0x0)
Can someone please explain what I am doing wrong?
Many thanks!
The issue you are experimenting is because in Swift Double
, Float
, Int
, etc, are not objects, but structs. You have to cast the value as a NSNumber
and then get the floatValue
from there. Something like this:
let dict:Dictionary <String, Any> = ["num": 100]
let cgf = dict["num"] as? NSNumber
NSLog("Float: %f", cgf!.floatValue)
let view = UIView()
view.frame = CGRectMake(CGFloat(cgf!.floatValue),200,10,10)
EDIT
if you are 100 percent the dictionary holds a value for the key then just do:
let cgf = dict["num"] as NSNumber
let view = UIView()
view.frame = CGRectMake(CGFloat(cgf.floatValue),200,10,10)
“Any can represent an instance of any type at all, including function types”
Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks. https://itun.es/tw/jEUH0.l
Any
can't force downcast to Double
.
Your dictionary can contain objects of any type, force downcast will not always succeed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With