SwiftUI-Day10 类和继承

文章目录

  • 吐槽
  • 结果
  • 构造函数
  • 继承
  • override关键字 - 方法重载
  • final关键字 - 无子类
  • 对象复制
  • Deinitializers - 析构函数
  • Mutability - 可变性

吐槽

Xcode升级,什么appdelegate都没有了,现在全是swiftUI。。。
下面的代码是playground的代码,不是swiftUI View。
参考资料:
https://www.hackingwithswift.com/100/swiftui/10
时间:10 October, 2020

类与结构体有五个不同:

  1. 类没有构造函数,所以要自己写
  2. 类可继承,结构体没有
  3. 一个类对象赋值给另一个变量,则两个变量都指向同一内存,而一个结构体对象赋值给另一个变量,则两个变量是完全无关的对象
  4. 类有析构函数
  5. 类不需要mutating关键字

结果

运行快捷键:shift+command+回车
删除当前行:option+D

构造函数

class Dog {
    var name: String
    var breed: String

    init(name: String, breed: String) {
        self.name = name
        self.breed = breed
    }
}
let poppy = Dog(name: "Poppy", breed: "Poodle")

继承

class Dog {
    var name: String
    var breed: String

    init(name: String, breed: String) {
        self.name = name
        self.breed = breed
    }
}
class Poodle: Dog {
    init(name: String) {
        super.init(name: name, breed: "Poodle")
    }
}

override关键字 - 方法重载

class Dog {
    func makeNoise() {
        print("Woof!")
    }
}
class Poodle: Dog {
    override func makeNoise() {
        print("Yip!")
    }
}
let poppy = Poodle()
poppy.makeNoise()

final关键字 - 无子类

final class Dog {
    var name: String
    var breed: String

    init(name: String, breed: String) {
        self.name = name
        self.breed = breed
    }
}

对象复制

结果一个是Taylor Swift一个是Justin Bieber

class Singer {
    var name = "Taylor Swift"
}
var singer = Singer()
print(singer.name)
var singerCopy = singer
singerCopy.name = "Justin Bieber"
print(singer.name)

改为结构体之后始终是Taylor Swift

struct Singer {
    var name = "Taylor Swift"
}
var singer = Singer()
print(singer.name)
var singerCopy = singer
singerCopy.name = "Justin Bieber"
print(singer.name)

Deinitializers - 析构函数

class Person {
    var name = "John Doe"

    init() {
        print("\(name) is alive!")
    }

    func printGreeting() {
        print("Hello, I'm \(name)")
    }
    deinit {
    print("\(name) is no more!")
}
}

for _ in 1...3 {
    let person = Person()
    person.printGreeting()
}

Mutability - 可变性

前面结构体中说如果要改结构体中变量的值需要用Mutating关键字,而类中不需要用mutating关键字。

class Singer {
    var name = "Taylor Swift"
}

let taylor = Singer()
taylor.name = "Ed Sheeran"
print(taylor.name)
class Singer {
    let name = "Taylor Swift"
}

你可能感兴趣的:(swift)