Struct和Class的区别
- Struct是值类型,存储于栈区,所以少量内存用结构体
- Class是引用类型,存储于堆区,大量数据用类
怎么选取Class还是Struct呢?
- 内存选取
- 赋值机制用的KVO,KVC,选取类继承与NSObject
- 是否考虑继承关系
创建Player的结构体**
struct Player {
var name: String
var hignScore: Int = 0
var history: [Int] = []
init(_ name: String) {
self.name = name
}
}
var player = Player("Tomas")
给Player新增一个方法
extension Player {
mutating func updateScore(_ newScore: Int) {
history.append(newScore)
if hignScore < newScore {
print("\(newScore)! A new high score for \(name)!💐")
hignScore = newScore
}
}
}
player.updateScore(50)
//50! A new high score for Tomas!💐
实现codable和equatable方法
extension Player: Codable, Equatable {
}
let encoder = JSONEncoder()
try! encoder.encode(player)
print(player)
//Player(name: "Tomas", hignScore: 50, history: [50])
条件扩展:只有是Player结构体的数组 才增加这个方法
extension Collection where Element == Player {
func highestScoringPlayer() -> Player? {
return self.max(by: { $0.hignScore < $1.hignScore })
}
}
//使用
let players = getPlayers()
let ranked = players.sorted { (player1, player2) -> Bool in
player1.hignScore > player2.hignScore
}
let rankedNames = ranked.map { $0.name }
print(rankedNames)
var recordHolder = ""
if let bestPlayer = players.highestScoringPlayer() {
recordHolder = """
The record holder is \(bestPlayer.name),\
with a high score of \(bestPlayer.hignScore)!
"""
} else {
recordHolder = "No games have been played yet."
}
print(recordHolder)
let highestScore = players.highestScoringPlayer()?.hignScore ?? 0
print(highestScore)
//获取方法
func getPlayers() -> [Player] {
var players = [Player]()
var player = Player("Tomas")
player.updateScore(50)
players.append(player)
var player1 = Player("Shlly")
player1.updateScore(80)
players.append(player1)
return players
}