天天看點

Swift裡的類繼承,構造和析構代碼

敲敲打打,

每天差不多一個小時來學這個,

相信到時候再用XCODE,感覺會熟悉很多。。

class Counter {
	var count = 0
	func increment() {
		count += 1
	}
	func increment(by amount: Int) {
		count += amount
	}
	func reset() {
		count = 0
	}
}

let counter = Counter()
counter.increment()
print(counter.count)
print(counter.increment(by: 5))
print(counter.reset())

class Vehicle {
	var currentSpeed = 0.0
	var description: String {
		return "traveling at \(currentSpeed) miles per hour"
	}
	func makeNoise() {
		//nothing
	}
}

class Bicycle: Vehicle {
	var hasBasket = false
}

let bicycle = Bicycle()
bicycle.hasBasket = true

bicycle.currentSpeed = 15.0
print("Bicycle: \(bicycle.description)")


let someVehicle = Vehicle()
print("Vehicle: \(someVehicle.description)")

struct Fahrenheit {
	var temperature: Double
	init() {
		temperature = 32.0
	}
}

var f = Fahrenheit()
print("The default temperature is \(f.temperature) Fahrenheit")

struct Color {
	let red, green, blue: Double
	init(red: Double, green: Double, blue: Double) {
		self.red = red
		self.green = green
		self.blue = blue
	}
	
	init(white: Double) {
		red = white
		green = white
		blue = white
	}
}

let magenta = Color(red: 1.0, green: 0.0, blue: 1.0)
let halfGray = Color(white: 0.5)

print(magenta.red)
print(halfGray.red)

class Bank {
	static var coinsInBank = 10_000
	static func distribute(coins numberOfCoinsRequested: Int) -> Int {
		let numberOfCoinsToVend = min(numberOfCoinsRequested, coinsInBank)
		coinsInBank -= numberOfCoinsToVend
		return numberOfCoinsToVend
	}
	static func receive(coins: Int) {
		coinsInBank += coins
	}
}

class Player {
	var coinsInPurse: Int
	init(coins: Int) {
		coinsInPurse = Bank.distribute(coins: coins)
	}
	
	func win(coins: Int) {
		coinsInPurse += Bank.distribute(coins: coins)
	}
	deinit {
		Bank.receive(coins: coinsInPurse)
	}
}

var playerOne: Player? = Player(coins: 100)

print("A new player has joined the game with \(playerOne!.coinsInPurse) coins")