我做了一个程序来计算视图的总宽度/高度(有时我想要总宽度,有时我想要总高度)。唯一的问题是:如果我正在计算宽度,我想10
在总数中添加一个额外的。这是我当前的代码:
func calculateLengthOfAllViews(calculatingWidth: Bool) {
let views = [
UIView(frame: CGRect.zero),
UIView(frame: CGRect(x: 0, y: 0, width: 50, height: 50)),
UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 50))
]
var totalLength: CGFloat = 0
if calculatingWidth {
totalLength += 10 /// add extra 10 if calculating width
} else {
totalLength += 0
}
for view in views { /// add each view's width/height
let length: CGFloat
if calculatingWidth {
length = view.frame.width
} else {
length = view.frame.height
}
totalLength += length
}
print("Total length is \(totalLength)")
}
calculateLengthOfAllViews(calculatingWidth: true) /// Total length is 160.0
calculateLengthOfAllViews(calculatingWidth: false) /// Total length is 100.0
这工作正常。但是,我if calculatingWidth {
在两个地方重复,以确定:
- 是否添加额外的padding 10 padding
- 是否使用
view.frame.width
或view.frame.height
作为长度
第二个 if 语句是不必要的,因为它在每次迭代中总是计算相同的东西。
所以,我认为键路径是要走的路——我可以存储对第一个 if 语句.width
或.height
来自第一个 if 语句的引用。但是,如何在不“初始化”的情况下定义键路径?我想做这样的事情:
let keyPath: KeyPath /// Reference to generic type 'KeyPath' requires arguments in <...>
if calculatingWidth {
totalLength += 10
keyPath = \UIView.frame.width
} else {
totalLength += 0
keyPath = \UIView.frame.height
}
for view in views {
let length = view[keyPath: keyPath] /// Type of expression is ambiguous without more context
totalLength += length
}
但是,这给了我Reference to generic type 'KeyPath' requires arguments in <...>
. 我怎样才能解决这个问题?