从零开始自学Swift(七)

前端之家收集整理的这篇文章主要介绍了从零开始自学Swift(七)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

类与结构体的计算属性

/*定义一个点*/
struct Point {
    var x:Double!,y:Double!
}
/*定义矩形的宽高*/
struct Size {
    var width:Double!,height:Double!
}
/*定义一个矩形*/
struct Rect {
    var origin=Point()
    var size=Size()
    var center:Point{
        get{
            let centerX=origin.x+(size.width/2)
            let centerY=origin.y+(size.height/2)
            return Point(x: centerX,y: centerY)
        }
        set(newCenter){
            origin.x=newCenter.x-(size.width/2)
            origin.y=newCenter.y-(size.height/2)
        }
    }
}

var rectangular=Rect(origin: Point(x: 0,y:0),size: Size(width: 2,height: 2))
print(rectangular.center)

下标脚本

关键词subscript

/*下标脚本*/
struct TiMetable {
    let multiplier:Int
    subscript (index:Int)->Int{
        return multiplier*index
    }
}
let fourTiMetable=TiMetable(multiplier: 4)
print(fourTiMetable[8])//32

猜你在找的Swift相关文章