Home > OS >  reduce the function by changing the operator
reduce the function by changing the operator

Time:07-29

I have a function with an expression. the different cases resemble much simply the operator <= or >= change Is it possible to simplify this function?

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
        }
    }

CodePudding user response:

Operators are actually regular functions in Swift, so you can save them to a closure, you just have to wrap the operator in parentheses.

Then you can call the operator like a regular closure and pass in the input arguments.

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
}
  • Related