美文网首页
swift的Struct学习-1

swift的Struct学习-1

作者: v尽栗而为v | 来源:发表于2020-06-29 10:25 被阅读0次

Struct和Class的区别

  • 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
}
今日份学习完毕,嘻嘻。搬砖啦

相关文章

  • swift的Struct学习-1

    Struct和Class的区别 Struct是值类型,存储于栈区,所以少量内存用结构体 Class是引用类型,存储...

  • iOS知识点总结(面试向)更新中

    Swift 1.Swift中struct和class的区别 Swift中struct和class有什么不一样的地方...

  • swift上struct和class的区别

    前言 struct和class是swift的两大数据结构,理解struct和class对我们学习swift的帮值很...

  • 面试题二

    Swift 1、Swift中struct和class有什么区别? struct是值引用,更轻量,存放于栈区,cla...

  • swift-struct作为数据模型

    struct的不足:1.当项目是swift和oc混合开发时,OC无法调用swift的struct,因为oc调用sw...

  • SwiftUI No.1

    swift是一种混合了面向对象变成,函数式编程,协议式编程的语言 1. Struct swift中的struct叫...

  • swift相关|基础知识

    swift: 1.struct和class区别 1.property初始化的不同 2.赋值不同struct 赋值“...

  • Swift中,Struct在栈区,Class对象分配在堆区?

    学习Swift时,有各种Struct和Class的比较,不少博客,指出Struct速度快,分配在栈区,而Class...

  • swift我们应该知道的

    1.class 和 struct 的区别? swift中,class是引用类型,struct是值类型。值类型在传递...

  • swift和OC对比

    swift和OC对比: 1.转模型时,swift经常用struct,而OC中用类,为什么? swift用struc...

网友评论

      本文标题:swift的Struct学习-1

      本文链接:https://www.haomeiwen.com/subject/lpnnfktx.html