Swift Extension 扩展

前端之家收集整理的这篇文章主要介绍了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

原文链接:https://www.f2er.com/swift/322126.html

猜你在找的Swift相关文章