2017-04-22 2 views
1

나는 모두 CGFloat가 필요합니다.Swift에서 CGFloat를 Any로 변환하는 방법 3

하지만 치명적인 오류가 발생했습니다. CGFloat에 Any를 할당 할 수없는 이유는 무엇입니까? 변환하는 방법?

let lx = ix as! CGFloat 

오류 메시지 :

스레드 1 : EXC_BAD_INSTRUCTION (코드 = EXC_l386_INVOP, 서브 코드 = 0x0으로)

0x1040dcbf1 < 1,329>는 : -0xc0 (%의 RBP) %의 XMM0 movsd; XMM0 MEM = [0], 제로

인쇄 로그 :

CGFloat : -0.5

CGFloat : -0.5

번호 :

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

답변

2

ix 및이 될 수 있습니다.은 Double이지만 CGFloat은 아닙니다. 먼저 Double으로 변환하려고 시도하면 DoubleCGFloat으로 쉽게 변환 할 수 있습니다.

let lx = CGFloat(ix as? Double ?? 0) 
let ly = CGFloat(iy as? Double ?? 0) 
관련 문제