gpt4 book ai didi

swift - 如何在 Swift 3 中将 Any 转换为 CGFloat

转载 作者:搜寻专家 更新时间:2023-10-31 22:05:16 25 4
gpt4 key购买 nike

我需要 Any 到 CGFloat。

但是,我遇到了一个 fatal error 。为什么不能将 Any 分配给 CGFloat?如何转换?

let lx = ix as! CGFloat

错误信息:

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

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

打印日志:

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

最佳答案

可能是 ixiy 只是 Double 但不是 CGFloat,首先尝试将其转换为Double 然后你可以轻松地将 Double 转换为 CGFloat

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

关于swift - 如何在 Swift 3 中将 Any 转换为 CGFloat,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43556118/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com