属性、方法、下标
属性
- Swift中跟实例相关的属性可以分为2大类
- 存储属性(Stored Property)
- 类似于成员变量这个概念
- 存储在实例的内存中
- 结构体、类可以定义存储属性 ü 枚举不可以定义存储属性
- 计算属性(Computed Property)
- 本质就是方法(函数)
- 不占用实例的内存
- 枚举、结构体、类都可以定义计算属性
struct Circle { // 存储属性
var radius: Double
// 计算属性
var diameter: Double {
set {
radius = newValue / 2
} get {
radius * 2
}
}
}
var circle = Circle(radius: 5)
print(circle.radius) // 5.0
print(circle.diameter) // 10.0
circle.diameter = 12
print(circle.radius) // 6.0
print(circle.diameter) // 12.0
print(MemoryLayout<Circle>.stride) // 8
存储属性
- 关于存储属性,Swift有个明确的规定
- 在创建类 或 结构体的实例时,必须为所有的存储属性设置一个合适的初始值
- 可以在初始化器里为存储属性设置一个初始值
- 可以分配一个默认的属性值作为属性定义的一部分
- 在创建类 或 结构体的实例时,必须为所有的存储属性设置一个合适的初始值
计算属性
set
传入的新值默认叫做``newValue,也可以自定义
struct Circle {
var radius: Double
var diameter: Double {
set(newDiameter) {
radius = newDiameter / 2
}
get {
radius * 2
}
}
}
- 定义计算属性只能用
var
,不能用let
let
代表常量:值是一成不变的- 计算属性的值是可能发生变化的(即使是只读计算属性)
- 只读计算属性:只有
get
,没有set
struct Circle {
var radius: Double
var diameter: Double {
get {
radius * 2
}
}
}
struct Circle {
var radius: Double
var diameter: Double { radius * 2 }
}
枚举rawValue原理
- 枚举原始值rawValue的本质是:只读计算属性
enum TestEnum : Int {
case test1 = 1, test2 = 2, test3 = 3
var rawValue: Int {
switch self {
case .test1:
return 10
case .test2:
return 11
case .test3:
return 12
}
}
}
print(TestEnum.test3.rawValue) // 12
延迟存储属性(Lazy Stored Property)
- 使用
lazy
可以定义一个延迟存储属性,在第一次用到属性的时候才会进行初始化
class Car {
init() {
print("Car init!")
}
func run() {
print("Car is running!")
}
}
class Person {
lazy var car = Car()
init() {
print("Person init!")
}
func goOut() {
car.run()
}
}
let p = Person()
print("--------")
p.goOut()
//打印结果
Person init!
--------
Car init!
Car is running!
lazy
属性必须是var
,不能是let
- let必须在实例的初始化方法完成之前就拥有值
- 如果多条线程同时第一次访问
lazy
属性 - 无法保证属性只被初始化1次
class PhotoView {
lazy var image: Image = {
let url = "https://www.baidu.com/xx.png"
let data = Data(url: url)
return Image(data: data)
}()
}
延迟存储属性注意点
- 当结构体包含一个延迟存储属性时,只有
var
才能访问延迟存储属性- 因为延迟属性初始化时需要改变结构体的内存
属性观察器(Property Observer)
- 可以为非
lazy
的var存储属性
设置属性观察器 willSet
会传递新值,默认叫newValuedidSet
会传递旧值,默认叫oldValue- 在初始化器中设置属性值不会触发
willSet
和didSet
- 在属性定义时设置初始值也不会触发
willSet
和didSet
- 在属性定义时设置初始值也不会触发
struct Circle {
var radius: Double {
willSet {
print("willSet", newValue)
}
didSet {
print("didSet", oldValue, radius)
}
}
init() {
self.radius = 1.0
print("Circle init!")
}
}
// Circle init!
var circle = Circle()
// willSet 10.5
// didSet 1.0 10.5
circle.radius = 10.5
// 10.5
print(circle.radius)
全局变量、局部变量
- 属性观察器、计算属性的功能,同样可以应用在全局变量、局部变量身上
var num: Int {
get {
return 10
}
set {
print("setNum", newValue)
}
}
num = 11 // setNum 11
print(num) // 10
func test() {
var age = 10 {
willSet {
print("willSet", newValue)
}
didSet {
print("didSet", oldValue, age)
}
}
age = 11
// willSet 11
// didSet 10 11
}
test()
inout的再次研究
struct Shape {
var width: Int
var side: Int {
willSet {
print("willSetSide", newValue)
}
didSet {
print("didSetSide", oldValue, side)
}
}
var girth: Int {
set {
width = newValue / side
print("setGirth", newValue)
}
get {
print("getGirth")
return width * side
}
}
func show() {
print("width=\(width), side=\(side), girth=\(girth)")
}
}
func test(_ num: inout Int) {
num = 20
}
var s = Shape(width: 10, side: 4)
test(&s.width)
s.show()
print("----------")
test(&s.side)
s.show()
print("----------")
test(&s.girth)
s.show()
//打印结果
getGirth
width=20, side=4, girth=80
----------
willSetSide 20
didSetSide 4 20
getGirth
width=20, side=20, girth=400
----------
getGirth
setGirth 20
getGirth
width=1, side=20, girth=20
inout的本质总结
- 如果实参有物理内存地址,且没有设置属性观察器
- 直接将实参的内存地址传入函数(实参进行引用传递)
- 如果实参是计算属性 或者 设置了属性观察器
- 采取了Copy In Copy Out的做法
- 调用该函数时,先复制实参的值,产生副本【get】
- 将副本的内存地址传入函数(副本进行引用传递),在函数内部可以修改副本的值
- 函数返回后,再将副本的值覆盖实参的值【set】
- 采取了Copy In Copy Out的做法
- 总结:inout的本质就是引用传递(地址传递)
类型属性(Type Property)
- 严格来说,属性可以分为
- 实例属性(Instance Property):只能通过实例去访问
- 存储实例属性(Stored Instance Property):存储在实例的内存中,每个实例都有1份
- 计算实例属性(Computed Instance Property)
- 类型属性(Type Property):只能通过类型去访问
- 存储类型属性(Stored Type Property):整个程序运行过程中,就只有1份内存(类似于全局变量)
- 计算类型属性(Computed Type Property)
- 实例属性(Instance Property):只能通过实例去访问
- 可以通过static定义类型属性
- 如果是类,也可以用关键字class
struct Car {
static var count: Int = 0
init() {
Car.count += 1 }
}
let c1 = Car()
let c2 = Car()
let c3 = Car() print(Car.count) // 3
类型属性细节
- 不同于存储实例属性,你必须给存储类型属性设定初始值
- 因为类型没有像实例那样的
init
初始化器来初始化存储属性
- 因为类型没有像实例那样的
- 存储类型属性默认就是
lazy
,会在第一次使用的时候才初始化 - 就算被多个线程同时访问,保证只会初始化一次
- 存储类型属性可以是
let
- 枚举类型也可以定义类型属性(存储类型属性、计算类型属性)
单例模式
public class FileManager {
public static let shared = FileManager()
private init() { }
}
public class FileManager {
public static let shared = {
// ....
// ....
return FileManager()
}()
private init() { }
}
方法(Method)
- 枚举、结构体、类都可以定义实例方法、类型方法
- 实例方法(Instance Method):通过实例对象调用
- 类型方法(Type Method):通过类型调用,用
static
或者class
关键字定义
- self
- 在实例方法中代表实例对象
- 在类型方法中代表类型
- 在类型方法
static
func
getCount
中cout
等价于self.cout
、Car.self.cout
、Car.cout
class Car {
static var cout = 0
init() {
Car.cout += 1 }
static func getCount() -> Int { cout }
}
let c0 = Car()
let c1 = Car()
let c2 = Car()
print(Car.getCount()) // 3
mutating
- 结构体和枚举是值类型,默认情况下,值类型的属性不能被自身的实例方法修改
- 在
func
关键字前加mutating
可以允许这种修改行为
- 在
struct Point {
var x = 0.0, y = 0.0
mutating func moveBy(deltaX: Double, deltaY: Double) {
x += deltaX
y += deltaY
// self = Point(x: x + deltaX, y: y + deltaY)
}
}
enum StateSwitch {
case low, middle, high
mutating func next() {
switch self {
case .low:
self = .middle
case .middle:
self = .high
case .high:
self = .low
}
}
}
@discardableResult
- 在
func
前面加个@discardableResult
,可以消除:函数调用后返回值未被使用的警告⚠️
struct Point {
var x = 0.0, y = 0.0
@discardableResult mutating
func moveX(deltaX: Double) -> Double {
x += deltaX
return x
}
}
var p = Point()
p.moveX(deltaX: 10)
@discardableResult
func get() -> Int {
return 10
}
get()
下标(subscript)
- 使用
subscript
可以给任意类型(枚举、结构体、类)增加下标功能,有些地方也翻译为:下标脚本subscript
的语法类似于实例方法、计算属性,本质就是方法(函数)
subscript
中定义的返回值类型决定了get
方法的返回值类型set
方法中newValue的类型
subscript
可以接受多个参数,并且类型任意
class Point {
var x = 0.0, y = 0.0
subscript(index: Int) -> Double {
set {
if index == 0 {
x = newValue
} else if index == 1 {
y = newValue
}
}
get {
if index == 0 {
return x
} else if index == 1 {
return y
}
return 0
}
}
}
var p = Point()
p[0] = 11.1
p[1] = 22.2
print(p.x) // 11.1
print(p.y) // 22.2
print(p[0]) // 11.1
print(p[1]) // 22.2
下标的细节
- subscript可以没有set方法,但必须要有get方法
- 如果只有get方法,可以省略get
class Point {
var x = 0.0, y = 0.0
subscript(index: Int) -> Double {
get {
if index == 0 {
return x
} else if index == 1 {
return y
}
return 0
}
}
}
class Point {
var x = 0.0, y = 0.0
subscript(index: Int) -> Double {
if index == 0 {
return x
} else if index == 1 {
return y
}
return 0
}
}
- 可以设置参数标签
class Point {
var x = 0.0, y = 0.0
subscript(index i: Int) -> Double {
if i == 0 {
return x
} else if i == 1 {
return y
}
return 0
}
}
var p = Point()
p.y = 22.2
print(p[index: 1]) // 22.2
- 下标可以是类型方法
class Sum {
static subscript(v1: Int, v2: Int) -> Int {
return v1 + v2
}
}
print(Sum[10, 20]) // 30
结构体、类作为返回值对比
class Point {
var x = 0, y = 0
}
class PointManager {
var point = Point()
subscript(index: Int) -> Point {
get { point }
}
}
struct Point {
var x = 0, y = 0
}
class PointManager {
var point = Point()
subscript(index: Int) -> Point {
set { point = newValue }
get { point } }
}
var pm = PointManager()
pm[0].x = 11
pm[0].y = 22
// Point(x: 11, y: 22)
print(pm[0])
// Point(x: 11, y: 22)
print(pm.point)
接收多个参数的下标
class Grid {
var data = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8]
]
subscript(row: Int, column: Int) -> Int {
set {
guard row >= 0 && row < 3 && column >= 0 && column < 3 else {
return
}
data[row][column] = newValue
}
get {
guard row >= 0 && row < 3 && column >= 0 && column < 3 else {
return 0
}
return data[row][column] }
}
}
var grid = Grid()
grid[0, 1] = 77
grid[1, 2] = 88
grid[2, 0] = 99
print(grid.data)