Search code examples
swiftswift3type-conversionanycgfloat

How to convert Any to CGFloat in Swift 3


I need Any to CGFloat.

But, I got a fatal error. Why can't assign Any to CGFloat? How to convert?

let lx = ix as! CGFloat

Error message:

Thread 1:EXC_BAD_INSTRUCTION (code=EXC_l386_INVOP, subcode=0x0)

0x1040dcbf1 <+1329>: movsd -0xc0(%rbp), %xmm0 ; xmm0 = mem[0],zero

Print Log:

CGFloat: -0.5

CGFloat: -0.5

Code:

import Foundation
    import UIKit

// creation of blocks
class Block {
    var blockRect = [Rectangle]()
    var type : String = String()
    var w : Int = Int()
    var h : Int = Int()
    var start_x = CGFloat()
    var start_y = CGFloat()
    var start_w_offset : Int? = Int()
    var blockView = UIView()
    
    func unwrap<T>(_ any: T) -> Any
    {
        let mirror = Mirror(reflecting: any)
        guard mirror.displayStyle == .optional, let first = mirror.children.first else {
            return any
        }
        return first.value
    }
   
    init(map : [NSDictionary], color : UIColor, view : UIView, block_view : UIView, x: CGFloat, w: Int, h: Int, type: String, start_w_offset: Int?) {
        self.blockView = block_view
        for i in map {
            
            let ix = unwrap(i["x"])
            let iy = unwrap(i["y"])
            
            print("CGFloat: \(ix)")
            print("CGFloat: \(iy)")
            
            let lx = ix as! CGFloat
            let ly = iy as! CGFloat
            let rd_x = x + lx * (size + padding)
            let rd_y = 450 + ly * (size + padding)
            let inner_x = block_view.frame.width/2 + lx * (size + padding)
            let inner_y = block_view.frame.height/2 + ly * (size + padding)
            self.start_x = x
            self.start_y = 0
            
            let r = Rectangle(type: "special", x: inner_x, y: inner_y, size: size, color: color, view: view, real_x : rd_x, real_y : rd_y)
            self.blockRect.append(r)
            self.type = type
            self.w = w
            self.start_w_offset = start_w_offset
            self.h = h
        }
    }
}

Solution

  • May be ix and iy is just Double but not the CGFloat, First try to convert it to Double then you can easily convert Double to CGFloat.

    let lx = CGFloat(ix as? Double ?? 0)
    let ly = CGFloat(iy as? Double ?? 0)