66 lines
2.0 KiB
Swift
66 lines
2.0 KiB
Swift
//
|
||
// CommonModels.swift
|
||
// Crush
|
||
//
|
||
// Created by Leon on 2025/8/30.
|
||
//
|
||
|
||
/// 通用数字类型,可解码 Int / Double / String,并可直接参与运算
|
||
struct FlexibleCGFloat: Codable {
|
||
var value: CGFloat
|
||
|
||
init(_ value: CGFloat) {
|
||
self.value = value
|
||
}
|
||
|
||
init(from decoder: Decoder) throws {
|
||
let container = try decoder.singleValueContainer()
|
||
if let intValue = try? container.decode(Int.self) {
|
||
value = CGFloat(intValue)
|
||
} else if let doubleValue = try? container.decode(Double.self) {
|
||
value = CGFloat(doubleValue)
|
||
} else if let stringValue = try? container.decode(String.self),
|
||
let doubleValue = Double(stringValue) {
|
||
value = CGFloat(doubleValue)
|
||
} else {
|
||
value = 0
|
||
}
|
||
}
|
||
|
||
func encode(to encoder: Encoder) throws {
|
||
var container = encoder.singleValueContainer()
|
||
try container.encode(Double(value))
|
||
}
|
||
}
|
||
|
||
// ✅ 支持字面量初始化
|
||
extension FlexibleCGFloat: ExpressibleByIntegerLiteral, ExpressibleByFloatLiteral {
|
||
init(integerLiteral value: Int) {
|
||
self.value = CGFloat(value)
|
||
}
|
||
init(floatLiteral value: Double) {
|
||
self.value = CGFloat(value)
|
||
}
|
||
}
|
||
|
||
// ✅ 支持常见运算符
|
||
extension FlexibleCGFloat {
|
||
static func + (lhs: FlexibleCGFloat, rhs: FlexibleCGFloat) -> FlexibleCGFloat {
|
||
return FlexibleCGFloat(lhs.value + rhs.value)
|
||
}
|
||
static func - (lhs: FlexibleCGFloat, rhs: FlexibleCGFloat) -> FlexibleCGFloat {
|
||
return FlexibleCGFloat(lhs.value - rhs.value)
|
||
}
|
||
static func * (lhs: FlexibleCGFloat, rhs: FlexibleCGFloat) -> FlexibleCGFloat {
|
||
return FlexibleCGFloat(lhs.value * rhs.value)
|
||
}
|
||
static func / (lhs: FlexibleCGFloat, rhs: FlexibleCGFloat) -> FlexibleCGFloat {
|
||
return FlexibleCGFloat(lhs.value / rhs.value)
|
||
}
|
||
}
|
||
|
||
// ✅ 方便和 CGFloat 互转
|
||
extension FlexibleCGFloat {
|
||
var cgFloat: CGFloat { value }
|
||
}
|