Visual_Novel_iOS/crush/Crush/Src/Models/CommonModels.swift

66 lines
2.0 KiB
Swift
Raw Normal View History

2025-10-09 10:29:35 +00:00
//
// 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 }
}