Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Dictionary Value to CGFloat in Swift

Tags:

swift

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!

like image 640
Jimmery Avatar asked Mar 18 '23 22:03

Jimmery


2 Answers

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)
like image 116
tkanzakic Avatar answered Apr 01 '23 07:04

tkanzakic


“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.

like image 44
ylin0x81 Avatar answered Apr 01 '23 08:04

ylin0x81