2017-04-22 28 views
1

J'ai besoin de Tout à CGFloat.Comment convertir n'importe quel à CGFloat dans Swift 3

Mais, j'ai eu une erreur fatale. Pourquoi ne peut-on attribuer Any à CGFloat? Comment convertir?

let lx = ix as! CGFloat 

message d'erreur:

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

0x1040dcbf1 < 1329>: movsd -0xc0 (% RBP),% xmm0; xmm0 = mem [0], zéro

Imprimer Connexion:

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 
     } 
    } 
} 

Répondre

2

Peut être ix et iy est juste Double mais pas le CGFloat, d'abord essayer de le convertir en Double alors vous pouvez facilement convertir Double en CGFloat.

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