swift的Struct学习-1

2020-06-29  本文已影响0人  v尽栗而为v

Struct和Class的区别

怎么选取Class还是Struct呢?

  1. 内存选取
  2. 赋值机制用的KVO,KVC,选取类继承与NSObject
  3. 是否考虑继承关系

创建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
}
今日份学习完毕,嘻嘻。搬砖啦
上一篇下一篇

猜你喜欢

热点阅读