我有一个有表达式的函数。不同的情况非常相似--操作符<=或>=的更改--可以简化这个函数吗?
func addEdgesLimit(corner: Corner, xOffset: CGFloat, yOffset: CGFloat, magnification:CGSize, imageSize: CGSize, cropSize: CGSize)->CGSize{
var magni = CGSize(width: magnification.width, height: magnification.height)
switch corner {
case .topLeft:
//Limit on the left edges of the screen
if xOffset <= (imageSize.width - cropSize.width) / 2{
magni.width = 1
}
//Limit on the top edges of the screen
if yOffset <= (imageSize.height - cropSize.height) / 2{
magni.height = 1
}
return magni
case .topRight:
//Limit on the right edges of the screen
if xOffset >= (imageSize.width - cropSize.width) / 2{
magni.width = 1
}
//Limit on the top edges of the screen
if yOffset <= (imageSize.height - cropSize.height) / 2{
magni.height = 1
}
return magni
case .bottomLeft:
//Limit on the left edges of the screen
if xOffset <= (imageSize.width - cropSize.width) / 2{
magni.width = 1
}
//Limit on the top edges of the screen
if yOffset >= (imageSize.height - cropSize.height) / 2{
magni.height = 1
}
return magni
}
}发布于 2022-07-28 09:28:51
运算符实际上是Swift中的常规函数,所以您可以将它们保存到闭包中,只需将运算符括起来即可。
然后,您可以像常规闭包一样调用运算符,并传入输入参数。
func addEdgesLimit(corner: Corner, xOffset: CGFloat, yOffset: CGFloat, magnification: CGSize, imageSize: CGSize, cropSize: CGSize)-> CGSize {
var magni = CGSize(width: magnification.width, height: magnification.height)
let xComparisonOperator: (CGFloat, CGFloat) -> Bool
let yComparisonOperator: (CGFloat, CGFloat) -> Bool
switch corner {
case .topLeft:
xComparisonOperator = (<=)
yComparisonOperator = (<=)
case .topRight:
xComparisonOperator = (>=)
yComparisonOperator = (<=)
case .bottomLeft:
xComparisonOperator = (<=)
yComparisonOperator = (>=)
}
if xComparisonOperator(xOffset, (imageSize.width - cropSize.width) / 2) {
magni.width = 1
}
if yComparisonOperator(yOffset, (imageSize.height - cropSize.height) / 2) {
magni.width = 1
}
return magni
}https://stackoverflow.com/questions/73150221
复制相似问题