首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >通过改变运算符来减少函数

通过改变运算符来减少函数
EN

Stack Overflow用户
提问于 2022-07-28 09:14:21
回答 1查看 48关注 0票数 -1

我有一个有表达式的函数。不同的情况非常相似--操作符<=或>=的更改--可以简化这个函数吗?

代码语言:javascript
复制
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
        }
    }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-07-28 09:28:51

运算符实际上是Swift中的常规函数,所以您可以将它们保存到闭包中,只需将运算符括起来即可。

然后,您可以像常规闭包一样调用运算符,并传入输入参数。

代码语言:javascript
复制
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
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73150221

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档