Swift Extension 扩展

Swift 里的Extension 和 OC 里的Catagory 差不多,很多细节会有差异,注释已写在代码里,请看注释

struct Point {
    var x = 0.0
    var y = 0.0
}

struct Size {
    var width = 0.0
    var height = 0.0
}

class Rectangle {
    var origin = Point()
    var size = Size()
    
    init(origin: Point, size: Size) {
        self.origin = origin
        self.size = size
    }
}

// 扩展方法
extension Rectangle {
    func translate(x: Double, y: Double) -> Void {
        self.origin.x += x
        self.origin.y += y
    }
}

// Swift 只能扩展计算型的属性,不能扩展存储型的属性
extension Rectangle {
    var center: Point {
        get {
            let x = self.origin.x + self.size.width/2
            let y = self.origin.y + self.size.height/2
            return Point(x: x, y: y)
        }
        
        set{
            self.origin.x = newValue.x - self.size.width/2
            self.origin.y = newValue.y - self.size.height/2
        }
    }
    
    // 只能扩展便利型的构造函数
    convenience init(center: Point, size: Size) {
        self.init(origin: Point(x: center.x - size.width/2, y: center.y - size.height/2), size: size)
    }
    
    //var borderWidth:Double = 1.0 // 声明一个边框的属性直接报错 Extension may not contain stored properties
}

// 嵌套枚举类型
extension Rectangle {
    enum Vertex {
        case leftTop
        case rightTop
        case leftBottom
        case rightBottom
    }
    
    func getPointWithVertex(vertex: Vertex) -> Point {
        switch vertex {
        case .leftTop:
            return self.origin
            
        case .rightTop:
            let x = self.origin.x + self.size.width;
            let y = self.origin.y
            return Point(x: x, y: y);
        
        case .leftBottom:
            let x = self.origin.x
            let y = self.origin.y + self.size.height
            return Point(x: x, y: y);
            
        case .rightBottom:
            let x = self.origin.x + self.size.width;
            let y = self.origin.y + self.size.height
            return Point(x: x, y: y);
            
        }
    }
}

var rect = Rectangle(origin: Point(x: 0, y: 0), size: Size(width: 10, height: 10))
print(rect.getPointWithVertex(vertex: Rectangle.Vertex.rightBottom)) // 两种方式都可以  ectangle.Vertex.rightBottom   .Vertex.rightBottom
print(rect.getPointWithVertex(vertex: .rightTop))

上面代码运行结果:

Point(x: 10.0, y: 10.0)

Point(x: 10.0, y: 0.0)


可以给系统的原有类型做扩展

// double 的扩展
extension Double{
    var km: Double {
        return self * 1000.0
    }
    
    var m:Double {
        return self
    }
    
    var cm: Double {
        return self/100.0
    }
    
    var ft: Double {
        return self/3.2804
    }
}

let runningDistance: Double = 5.00.km
print(runningDistance)

运行结果:

5000.0






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值