import UIKit
/*
* 本节主要内容:存储属性 / 计算型属性 / 类型属性 / 延迟加载属性
*/
// 类型属性(Type Property)
// 声明描述玩家类, 记录每个玩家的分数(存储属性), 记录所有玩家的分数(类型属性)
class Player {
// 名字
var name: String
// 分数
var score = 0 // Int
// 类型属性(static): 记录所有玩家的最高分
static var highestScore = 0
// init构造方法
init(name: String) {
self.name = name
}
// 自定义方法: 玩游戏
func play() {
// 1.随机产生数: 0 ~ 99
let score = Int(arc4random()%100)
print("\(name) played and got \(score) scores.")
// 2.score属性累加
self.score += score
// 3.判断, 更新最高分属性
if self.score > Player.highestScore {
Player.highestScore = self.score
}
print("Highest score is \(Player.highestScore)")
}
}
var playerOne = Player(name: "playerOne")
var playerTwo = Player(name: "playerTwo")
playerOne.play()
playerOne.play()
playerOne.score
playerTwo.play()
playerTwo.play()
playerTwo.score
/*
* 存储属性的属性观察器(Property Observer)机制: 对属性的获取/赋值做出相应反应;
* 1. 语法: willSet(将要赋值); didSet(已经赋值成功)
*/
// 基本语法使用; 声明显示音量的类, 一个存储属性, 描述level
class Volume {
// 原来: var level: Int = 0
// 包含属性观察器语法:
var level: Int = 0 {
// willSet {
// print("willSet......")
// // 获取将要赋值的新值
// print("willSet: \(newValue)")
// // 获取当前的level的值
// print("willSet: \(level)")
// }
// didSet {
// print("*****didSet......")
// // 获取原来老值
// print("*****didSet: \(oldValue)")
// // 获取当前已经赋值完的值
// print("*****didSet: \(level)")
// }
// 自定义关键词
willSet(newCustomValue) {
print("willSet......")
// 获取将要赋值的新值
print("willSet: \(newCustomValue)")
// 获取当前的level的值
print("willSet: \(level)")
}
didSet(oldCustomValue) {
print("*****didSet......")
// 获取原来老值
print("*****didSet: \(oldCustomValue)")
// 获取当前已经赋值完的值
print("*****didSet: \(level)")
}
}
}
// 实例化
var volume = Volume()
volume.level = 10
/*
声明描述灯泡类, 添加两个属性(当前通过灯泡的电流数; 灯泡可以通过的最大电流数), 使用属性观察器机制, 判定对灯泡电流数赋值的可行性
*/
class LightBulb {
// 类型属性: 灯泡可以通过的最大电流数
static let maxCurrent = 10 // A
// 存储属性: 当前通过灯泡的电流数
var current = 0 {
willSet {
// 判断将要赋值的电流数是否符合要求
if newValue > LightBulb.maxCurrent {
print("You cannot set current that high!")
// 电流跨度(变化)
print("Current value changed. The change is \(abs(newValue - current))")
}
}
didSet {
// 如果等于最大电流数, 显示警告
if current == LightBulb.maxCurrent {
print("Pay attention, the current value got to the maximum point.")
}
}
}
}
// 实例化
var lightBulb = LightBulb()
lightBulb.current = 2
lightBulb.current = 10
Swift 系统学习 24 类相关 存储属性 计算属性 类型属性 延迟加载属性
最新推荐文章于 2024-05-27 15:18:45 发布