class User7 {
let name: String
var age: Int
static var count = 0
init(_ name: String, _ age: Int){
self.name = name
self.age = age
User7.count += 1
}
static func getInfo(){
print("\(count) instances")
}
func printMessage(_ msg: String){
print("\(msg) \(name) \(age)")
}
}
User7.getInfo() //----- 0 instances
let user7 = User7("morita", 32)
User7.getInfo() //----- 1 instances
// なお staticは継承できない。継承したい場合は、static ではなく、classを使用する。
// 型キャスト
class User8 {
let name: String
init(_ name: String){
self.name = name
}
}
class AdminUser8: User8{}
let taro = User8("taro")
let jiro = AdminUser8("jiro")
let users8 = [taro, jiro]
for user8 in users8 {
if let u = user8 as? AdminUser8{
print(u.name) //----- jiro
}
}
protocol Drink {
var type: String { get } //読み込み専用
var count: Int { get set } //読み書きOK
func Sale()
}
class User9: Drink {
let name: String
let type = "tea"
var count = 0
init(_ name: String){
self.name = name
}
func Sale(){
count += 1
print("\(type): \(count)")
}
}
let taro9 = User9("taro")
taro9.Sale() //----- tean: 1
taro9.Sale() //----- tean: 2
taro9.Sale() //----- tean: 3