类型定义的语法
通过struct定义结构体
struct SomeStruct {
}
通过class定义类
class SomeClass {
}
定义一个结构体, 用于描述分辨率
width: 横向分辨率
height: 纵向分辨率
struct Resolution {
var width = 0
var height = 0
}
定义一个类, 用于描述显示器的某个特定视频模式
class VideoModel {
var resolution = Resolution()
var interlaced = false
var frameRate = 0.0
var name: String?
}
创建一个结构体的实例和一个类的实例
var someResolution = Resolution()
let someVideoModel = VideoModel()
结构体属性的访问
someResolution.width = 1280
someResolution.height = 960
print("the width is \(someResolution.width)")
print("the height is \(someResolution.height)")
类中的属性的访问
someVideoModel.resolution.width = 2560
someVideoModel.resolution.height = 1080
print("the width is \(someVideoModel.resolution.width)")
print("the height is \(someVideoModel.resolution.height)")
结构体类型的成员逐一构造器, 类实例没有默认的成员逐一构造器
let vga = Resolution(width: 640, height: 680)
结构体和枚举是值类型
值类型: 当它被赋值给一个变量, 常量或者传递给一个函数的时候, 其值会被拷贝
值类型有: 整型, 浮点型, 布尔型, 字符串, 数组, 字典
let hd = Resolution(width: 1920, height: 1080)
var cinema = hd
// 通过查看地址来证明结构体的赋值是值拷贝\
print("hd地址为: \(Unmanaged<AnyObject>.passUnretained(hd **as** AnyObject).toOpaque())")
print("cinema地址为: \(Unmanaged<AnyObject>.passUnretained(cinema **as** AnyObject).toOpaque())")
// 更改其中一个实例的值
cinema.width = 2048
print("the width of cinema is \(cinema.width)")
print("the width of hd is \(hd.width)")
枚举是值类型
enum CompassPoint {
case north, south, east, west
mutating func tunrNorth() {
self = .north
}
}
var currentDirection = CompassPoint.west
let rememberDirection = currentDirection
currentDirection.tunrNorth()
print("the current direction is \(currentDirection)")
print("the remember direction is \(rememberDirection)")
类是引用类型
引用类型在被赋值给一个变量, 常量或者传递给一个函数时, 其值不会被拷贝
let tenEighty = VideoModel()
tenEighty.resolution = hd
tenEighty.interlaced = true
tenEighty.name = "1080i"
tenEighty.frameRate = 25.0
相当于同一实例的两种叫法
let alsoTenEighty = tenEighty
alsoTenEighty.frameRate = 30
print("the frame rate is \(tenEighty.frameRate)")
恒等运算符 === !===
if tenEighty === alsoTenEighty {
print("tenEighty and alsoTenEight are same")
} else {
print("tenEighty and alsoTenEighty are different")
}