您的位置:首页 > 移动开发 > Swift

CYC-Swift高级开发语言--结构体,类,构造器,属性

2015-11-02 10:59 393 查看
// 结构体和类
// 在swift中,结构体被做了很多强化,几乎所有的数据类型都是用结构体实现的,
// 相同点:1.都可以定义变量 2.都可以定义方法 3.都可以定义构造器 init 4.都可以遵守歇息 5.扩展
// 不同点:1.结构体是值类型,类是引用类型 2.类可以被继承 3.类可以使用类型推断 4.类可以使用 deinit(析构器) 5.一个类可以有多个引用


结构体

// 结构体
struct Resolution {
// 定义变量 (属性)
var height = 0
var width = 0
}

// 结构体自动根据属性生成构造器(init方法)
let resolution = Resolution(height: 10, width: 10)
resolution.height
resolution.width




// 类
class Video {
var resolution_class = Resolution(height: 20, width: 20)
var frameRate = 0.1
}
// 类不会自动生成构造器,需要我们主动实现
let video = Video()
video.frameRate = 0.2
// 值类型和引用类型的区别
var newResolution =  resolution
newResolution.height = 29
newResolution.height
resolution.height
var newVideo = video
newVideo.frameRate
newVideo.frameRate = 0.5
newVideo.frameRate
video.frameRate


构造器

// 构造器
struct ResolutionA {
var height = 0
var width = 0
// 构造器,系统生成self.属性名 用于赋值
init(gao:Int, kuan:Int){
self.height = gao
self.width = kuan
}
}
let resolution2 = ResolutionA(gao: 10, kuan: 10)
resolution2.height

class VideoA {
var frameRate = 0.2
var resolution_VA = ResolutionA(gao: 20, kuan: 20)
// 构造器会自动生成外部参数名,构造器内实现对属性的赋值操作
init(frame:Double, resolu_VA:ResolutionA){
self.frameRate = frame
self.resolution_VA = resolu_VA
}
}

let videoA = VideoA(frame: 0.3, resolu_VA: resolution2)


属性

// 属性分为两种:计算属性和存储属性
// 存储属性:存储类和结构体里面的常量或变量,只起到存储作用
// 计算属性:不作为存储功能使用,计算属性本身提供get set方法,间接的获取计算属性的值

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

struct Size {
var with = 100
var heigth = 100
}

var point = Point(x:0, y:0)
// 代表正方形
struct Rect {
//
var point_z = Point(x: 0, y: 0)
var size = Size(with: 100, heigth: 100)
// 计算属性
var center:Point {
set{
// set方法中,自动生成newValue, 代表赋给的新值
// 平移
let x = newValue.x - size.with / 2
let y = newValue.y - size.heigth / 2
point_z.x = x
point_z.y = y

}
get{
// 在get方法中,用于获取属性的值
let centerX = point_z.x + size.with / 2
let centerY = point_z.y + size.heigth / 2
return Point(x: centerX, y: centerY)
}
}
}

var rect = Rect(point_z: Point(x: 0, y: 0), size: Size(with: 100, heigth: 100))
rect.center.x
rect.center = Point(x: 500, y: 500)
rect.point_z.x

// 定义方法
struct ResolutionB {
var height = 0
var with = 0
// 结构体定义方法
// 结构体方法默认不能对结构体属性做更改,如果有更改需求,需要使用mutating关键字对方法进行修饰
mutating func hello() {
print("你好")
func hello2() {
print("hello")
}
self.with = 20
}
// 类似于 + 方法  静态方法
static func helloWord() {
print("HelloWorld")

}
}

var resolution4 = ResolutionB()
resolution4.hello()

class VideoB {
var frameRate = 0.1
// 类里面的普通方法可以对类的属性做更改
func dj() {
print("~~~~~")
frameRate = 0.2

}
// +方法 类型方法
func djj() {
print("sdd")
}
// 类型属性,只能是计算属性,只实现get方法--只读
class var name:String {
get{
return "maomao"
}
}

}

var video3 = VideoB()
video3.dj()
//VideoB.djj()
VideoB.name
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  开发语言