博客> swift 重命名+-*/=,让它们更强大,为你所用
swift 重命名+-*/=,让它们更强大,为你所用
2018-05-20 23:33 评论:0 阅读:439 IT喃

直接创建一个新的类:MyUtils.swift 将其代码改成如下:

import UIKit
import Foundation
import CoreGraphics

func + (left: CGPoint, right: CGPoint) -> CGPoint {
    return CGPoint(x: left.x + right.x, y: left.y + right.y)
}

func += ( left: inout CGPoint, right: CGPoint) {
    left = left + right
}

func - (left: CGPoint, right:CGPoint) -> CGPoint {
    return CGPoint(x: left.x - right.x, y: left.y - right.y)
}

func -= (left: inout CGPoint, right: CGPoint) {
    left = left - right
}

func * (left: CGPoint, right: CGPoint) -> CGPoint {
    return CGPoint(x: left.x * right.x, y: left.y * right.y)
}

func *= (left: inout CGPoint, right: CGPoint) {
    left = left * right
}

func * (point: CGPoint, scalar: CGFloat) -> CGPoint {
    return CGPoint(x: point.x * scalar, y: point.y * scalar)
}

func *= (point: inout CGPoint, scalar: CGFloat) {
    point = point * scalar
}

func / (left: CGPoint, right: CGPoint) -> CGPoint {
    return CGPoint(x: left.x / right.x, y: left.y / right.y)
}

func /= (left:inout CGPoint, right: CGPoint) {
    left = left / right
}

func / (point: CGPoint, scalar: CGFloat) -> CGPoint {
    return CGPoint(x: point.x / scalar, y: point.y / scalar)
}

func /= (point:inout CGPoint, scalar: CGFloat) {
    point = point / scalar
}

let test1 = CGPoint(x: 100, y: 100)
let test2 = CGPoint(x: 50, y: 50)
let test5: CGFloat = 10.1
let test3 = test1 + test2
let test6 = test1 / test5

func addPlusMethod() {
    print("doubi \(test3) and \(test6)")
}
// 在另一个类中调用 addPlusMethod()方法,打印出结果如下
打印结果如下:

// 这里我们只是测试了一下加方法和除方法,其他的小伙伴们可以自己试一下

doubi (150.0, 150.0) and (9.9009900990099, 9.9009900990099)

当然,还有atan和sqrt方法,小伙伴们也可以自己试一下,(๑•̀ㅂ•́)و✧加油

// 2017年11月16日 更新O(∩_∩)O~ 现在又添加了两个,看一下是不是挺好玩

#if !(arch(x86_64) || arch(arm64))
    func atan2(y: CGFloat, x: CGFloat) -> CGFloat {
        return CGFloat(atan2f(Float(y),Float(x)))
    }

    func sqrt(a: CGFloat) -> CGFloat {
        return CGFloat(sqrtf(Float(a)))
    }
#endif
收藏
0
sina weixin mail 回到顶部