- 类的初探
class Person {
let firstName: String
let lastName: String
var career: String?
init(firstName: String, lastName: String, career: String) {
self.firstName = firstName
self.lastName = lastName
self.career = career
}
init(firstName: String, lastName: String) {
self.firstName = firstName
self.lastName = lastName
}
func fullName() -> String {
return firstName + " " + lastName
}
}
let person = Person(firstName: "qin", lastName: "zhen", career: "programmer")
person.fullName()
- 添加一个新的方法(方法可以改变对象的值)
func setNewCareer(newCareer: String) {
self.career = newCareer
}
//对于引用类型而言,变量的实例是一个常量的话,依然可以修改定义在类中可变量的值,且可以通过方法直接修改实例本身
person.setNewCareer(newCareer: "freelancer") //不报错
- 引用类型对比值类型
// 方法前不加mutating关键字会报错
//类比结构体
struct Location {
var x: Int = 0
var y: Int = 0
mutating func goEast(){
self.x += 1 //如果不加mutating则报错,x不可修改
}
}
var location = Location()
location.goEast()
//类比枚举
enum Switch {
case On
case Off
mutating func click() {
switch self {
case .On:
self = .Off
case .Off:
self = .On
}
}
}
var button = Switch.Off
button.click()
- 引用类型的比较
let person1 = Person(firstName: "qin", lastName: "zhen", career: "programmer")
let person2 = person
//person2 == person1 //报错
person2 === person1 //true,判断两个对象是否指向同一块内存空间,符号适用于引用类型
let person3 = Person(firstName: "qin", lastName: "zhen", career: "programmer")
person3 === person1 //false,person1和person3分别指向两块不同的内存空间
person3 !== person1 //true
- 什么时候用结构体,什么时候用类
- 把结构看作是值:位置(经纬度),坐标(二维、三维坐标),温度等(栈)
- 把类看作是物体:人、车、商品、动物等 (堆)
- 计算型属性
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()
//计算型属性必须声明为var
var center: Point {
// getter和setter方法
get {
let centerX = origin.x + size.width / 2
let centerY = origin.y + size.height / 2
return Point(x: centerX, y: centerY)
}
set {
origin.x = newValue.x - size.width / 2
origin.y = newValue.y - size.height / 2
}
}
init(origin: Point, size: Size) {
self.origin = origin
self.size = size
}
//如果只是取值,直接return即可
var area: Double {
return size.height * size.width
}
}
var rec = Rectangle(origin: Point(), size: Size(width: 10, height: 10))
//使用get方法获取属性值
rec.center
//使用set方法修改center坐标
rec.center = Point()