主要是讲 struct 和 class
struct 主要用于数据,所以复制的情况下是硬拷贝,数据互相直接没有关系
class 由于有继承,默认复制是引用,数据之间互相影响
struct
struct Album{
let title:String //property
let artist:String//property
var year:Int
//struct 自带 init,除非要自定义,否则无需写出来
// init(title: String, artist: String, year: Int) { automatically set
// self.title = title
// self.artist = artist
// self.year = year
// }
func printSummary(){
print("(title) (artist) (year)")
}
// func addYear(num:Int)
// {
// year += num //cant modify //struct 默认是不能改变数据的
// }
mutating func addYear(num:Int)//use mutating//使用 mutating 表示可以修改数据
{
year += num //cant modify
}
//计算属性,根据其他数据自动算出该数据,必须声明类型
//computing property only with var
//computing property must define data type
var halfoftheYear:Int{ //computing property set automatically
year/2
}
//计算属性可以分别定义 get 和 set,newValue 是赋值的数据
var addYear2:Int{ //computing property set when newvalue is given
get{
year
}
set{
year + newValue
}
}
}
var blue = Album.init(title:"blue",artist: "Jap",year: 1991)
var red = Album(title:"Red",artist: "Jap",year: 1991) //sytax sugar,省略 init 的语法糖
let balck = Album(title:"black",artist: "Jap",year: 1991)
//let balck2 = Album(title:"black",artist: "Jap")
red.addYear(num: 10)
red.printSummary()
red.halfoftheYear
red.addYear2 = 500 //set
red.addYear2 //get
let a = 1
let b = 1.0
let c = Double(a)+b //actually here is strcut init 这其实这也是 struct
//property observer //also be a type of computing property
struct Game{
var score = 0 {
didSet{ //execute after every update didSet 会在赋值更新后执行
print("Score is now (score)")
}
willSet{//execute before every update
print("old Score is (score)") willSet 会在赋值更新 执行
}
}
}
var game = Game()
game.score += 1
struct BankAccount {
var name: String
var isMillionnaire = false
var balance: Int { //update isMillionaire when changing
didSet {
if balance > 1_000_000 {
isMillionnaire = true
} else {
isMillionnaire = false
}
}
}
}
var backaccount = BankAccount(name: "zu", balance: 100)
backaccount.isMillionnaire
//权限,就是 public private,swift 里还有一个 fileprivate,在该文件内可以直接访问
//access control
struct BankAccount1{
private var funds = 0
fileprivate var funds1 = 0 // only this file can use
private(set) var funds2 = 0 // can read directly
mutating func desposit(amount:Int){
funds += amount
}
mutating func withdraw(amount: Int){
funds -= amount
}
func show(){
print(funds)
}
}
var accout = BankAccount1()
accout.desposit(amount: 1000)
accout.withdraw(amount: 100)
print(accout.show())
accout.funds1
accout.funds2
//accout.funds2 += 10
//自定义 初始化,注意没有 func 和 return
//custom initializers
struct Player{
let name:String
let number:Int
init(name_input: String, number: Int) { //no func, no return
name = name_input
self.number = number + 1 //need self to tell them
}
}
//注意private 不会自动 init,必须赋值或者自定义 init
//struct Doctor {
// var name: String
// var location: String
// private var currentPatient = "No one" //init cant access it so a custom init should be wirte
//// init(name: String, location: String, currentPatient: String = "No one") {
//// self.name = name
//// self.location = location
//// self.currentPatient = currentPatient
//// }
//}
//let drJones = Doctor(name: "Esther Jones", location: "Bristol")
//static 表示超越 instance 的,对struct 本身的描述
//static properties and methods
struct School{
let name:String
static var studentCount:Int = 0
static func add(student:String)
{
print("(student) join the school!")
studentCount += 1
}
// func readCount(){
// print("count:(self.studentCount)")//counldnt read the static property in instance //instance 不能直接读取 static 属性
// }
func readCount(){ //use uppercase Self to infer the struct type
print("count:(Self.studentCount)")//用 Self(首字母大写) 表示结构本身,可读取 static 属性
}
//use static property to make an example
static let example = School(name: "best school")
}
School.studentCount += 1
School.add(student: "jay")
School.studentCount
var school = School(name: "medium")
school.readCount()
School.example.name
Class
注意 Class 里的 Constant 属性依然可以被改变(直接常数变量赋值无法改变,但其他指向同一个目标的动态变量就可以改变)
//class initializer inheriance
class Vehicle{
let isElectric: Bool
init(isElectric: Bool) { //class 和 struct 不同,有属性就必须自定义 init,不能省略,主要是因为有继承,编译器不好判断
self.isElectric = isElectric
}
}
class Car:Vehicle{
let isContiable: Bool
init(isElectric:Bool, isContiable: Bool) { //add parent param //重构 init 的情况下,原参数也要加上
self.isContiable = isContiable
super.init(isElectric: isElectric) // required 原参数的写法
}
}
final class Bike:Car{ //final means not allowed inherance further //使用 final 可以定义不能被继承
let manualable = false
}
//普通的赋值会指向同一个 instance ,而不是复制
//hard copy class and deinit
class Class1{
var name :String
init(name: String) {
self.name = name
}
func hardCopy(name:String) -> Class1{ //class no need mutating
let newInstance = Class1(name:name)
return newInstance
}
deinit{ //可以自定义 deinit,但没有“()”更没有 return
print("(self.name) is all destoryed")
}
}
if 1 == 1{
var aa = Class1(name: "a")
var bb = aa.hardCopy(name: "b")
var cc = aa
aa.name
bb.name
cc.name
}