我正在尝试将存储在字典中的值转换为 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)
Run Code Online (Sandbox Code Playgroud)
这会导致运行时错误:
Thread 1: EXC_BREAKPOINT (code=EXC_I386_BPT, subcode=0x0)
Run Code Online (Sandbox Code Playgroud)
有人可以解释一下我做错了什么吗?
非常感谢!
您正在试验的问题是因为在 Swift 中Double,Float, Int, 等不是对象,而是结构。您必须将值转换为 a NSNumber,然后floatValue从那里获取。像这样的东西:
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)
Run Code Online (Sandbox Code Playgroud)
编辑
如果您是 100% 字典保存键的值,那么只需执行以下操作:
let cgf = dict["num"] as NSNumber
let view = UIView()
view.frame = CGRectMake(CGFloat(cgf.floatValue),200,10,10)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2672 次 |
| 最近记录: |