100 Days of Swift - Day 08 - 结构体

2022-12-22  本文已影响0人  NieFeng1024

100 Days of Swift - Day 08 - 结构体(Structs part 1)

8.1 创建自定义结构 Struct

struct Sport {
    var name: String
}
var tennis = Sport(name: "Tennis")
print(tennis.name)
tennis.name = "Lawn tennis"
结构体和元组都可以构建包含多个属性的自定义结构,但又有本质却别。
元组可以认为是一个匿名拥有固定属性的结构体常量,通常在函数参数或者返回值需要多个数据项时使用,一旦创建不能修改,只能复制代码。
结构体拥有天然优势,可以根据需求变更增删属性,可以重复使用。
// 结构体
func authenticate(_ user: User) { ... }
func showProfile(for user: User) { ... }
func signOut(_ user: User) { ... }
// 元组
func authenticate(_ user: (name: String, age: Int, city: String)) { ... }
func showProfile(for user: (name: String, age: Int, city: String)) { ... }
func signOut(_ user: (name: String, age: Int, city: String)) { ... }

8.2 计算属性 Computed properties

struct Sport {
    // 存储属性
    var name: String
    var isOlympicSport: Bool
    // 计算属性
    var olympicStatus: String {
        if isOlympicSport {
            return "\(name) is an Olympic sport"
        } else {
            return "\(name) is not an Olympic sport"
        }
    }
}
let chessBoxing = Sport(name: "Chessboxing", isOlympicSport: false)
print(chessBoxing.olympicStatus)
let pingPang = Sport(name: "PingPang", isOlympicSport: true)
print(pingPang.olympicStatus)
// Chessboxing is not an Olympic sport
// PingPang is an Olympic sport

8.3 属性监听Property observers

struct Progress {
    var task: String
    var amount: Int
}
// 初始化设置金额
var progress = Progress(task: "Loading data", amount: 0)
// 修改金额
progress.amount = 30
// 修改金额
progress.amount = 80
// 修改金额
progress.amount = 100
struct Progress {
    var task: String
    var amount: Int {
        willSet {
            print("willSet \(task) is now \(amount)%")
        }
        didSet {
            print("complete \(task) is now \(amount)%")
        }
    }
}
var paly = Progress(task: "paly", amount: 10)
paly.amount = 20
// willSet paly is now 10%
// complete paly is now 20%

8.4 方法Methods

struct City {
    var population: Int

    func collectTaxes() -> Int {
        return population * 1000
    }
}
let london = City(population: 9_000_000)
london.collectTaxes()

8.4 Mutating methods

struct Person {
    // 1. 属性变量
    var name: String
    // 2. 使用mutating 关键字修饰方法,在方法内修改属性
    mutating func makeAnonymous() {
        name = "Anonymous"
    }
}
// 3. 创建结构体变量
var p = Person(name: "Eric")
print(p.name)
// 4. 调用方法修改属性
p.makeAnonymous()
print(p.name)
// person name is: Eric
// person name is: Anonymous
  1. 结构体常量无法调用mutating修饰的方法,即时该方法没有修改属性。
  2. 未被mutating修饰的方法无法调用被mutating修饰的方法。

8.5 字符串属性和常用方法

  1. 创建一个字符串用于测试实验
let string = "Do or do not, there is no try."
  1. 获取字符串个数的属性
print(string.count)
// 30
  1. 获取字符串是否包含前缀方法
print(string.hasPrefix("Do"))
// true
  1. 转为大写字母方法
print(string.uppercased())
// DO OR DO NOT, THERE IS NO TRY.
  1. 排序方法
print(string.sorted())
// [" ", " ", " ", " ", " ", " ", " ", ",", ".", "D", "d", "e", "e", "h", "i", "n", "n", "o", "o", "o", "o", "o", "r", "r", "r", "s", "t", "t", "t", "y"]

8.6 数组的属性和常用方法

var toys = ["Woody"]
print(toys.count)
// 1
toys.append("Buzz")
print(toys)
// ["Woody", "Buzz"]
let result = toys.firstIndex(of: "Buzz") ?? 0
print(result)
// 1
print(toys.sorted())
// ["Buzz", "Woody"]
print(toys)
// ["Woody", "Buzz"]
toys.remove(at: 0)
print(toys)
// ["Buzz"]

声明:本文创作来自hackingwithswift

上一篇下一篇

猜你喜欢

热点阅读