【发布时间】:2019-03-31 06:08:21
【问题描述】:
我有一个协议 (EasyPosTypes),其中包含应该能够分配给变量的所有类型。
protocol EasyPosTypes { }
protocol EasyPosStandardTypes { }
extension EPPercentage: EasyPosTypes { }
extension Int: EasyPosTypes, EasyPosStandardTypes { }
extension CGFloat: EasyPosTypes, EasyPosStandardTypes { }
extension Double: EasyPosTypes, EasyPosStandardTypes { }
extension Float: EasyPosTypes, EasyPosStandardTypes { }
然后我有了变量,x和y应该可以是上面定义的类型(EasyPosTypes):
struct FrameComponent {
var screenWidth = UIScreen.main.bounds.width
var screenHeight = UIScreen.main.bounds.height
var width: CGFloat = 0.0
var height: CGFloat = 0.0
var x: EasyPosTypes = 0.0
var y: EasyPosTypes = 0.0
var percentX: CGFloat = -1
var percentY: CGFloat = -1
}
protocol EasyPos {
var fc: FrameComponent { get set }
func update()
}
在这里我想测试类型。除了 EPPercent 我想在 if 语句中运行代码,对于 EPPercent 我想在 else if 中运行 on:
extension EasyPos where Self: UIView {
func update() {
if let xFloat = fc.x as? EasyPosStandardTypes {
frame = CGRect(x: CGFloat(xFloat), y: frame.minY, width: frame.width, height: frame.height)
} else if let xPercent = fc.x as? EPPercent {
frame = CGRect(x: fc.screenWidth * CGFloat(xPercent) - frame.width / 2, y: frame.minY, width: frame.width, height: frame.height)
}
}
}
if 中的代码给出以下错误:
“无法使用类型为 '(EasyPosStandardTypes)' 的参数列表调用类型 'CGFloat' 的初始化程序”
else中的代码:
“无法使用类型为 '(EPPercent)' 的参数列表调用类型为 'CGFloat' 的初始化程序”
【问题讨论】:
-
你不想改用 typealias 吗?