class User { let name: String // property var score: Int // init(name: String, score: Int){ init(_ name: String,_ score: Int){ self.name = name self.score = score } init(){ self.name = "bob" self.score = 30 } } // let tom = User(name: "tom", score: 23) let tom = User("tom", 23) print(tom.name) print(tom.score) let bob = User() print(bob.name) print(bob.score)
計算プロパティ
class User { let name: String // property var score: Int var level: Int{ get { return Int(score / 10) } set { if newValue >= 0 { score = newValue * 10 } } } init(_ name: String,_ score: Int){ self.name = name self.score = score } init(){ self.name = "bob" self.score = 30 } } let tom = User("tom", 23) print(tom.level) tom.level = 5 print(tom.score)
willSetとdidSet
let name: String // property var score: Int { willSet { // before change print("\(score) -> \(newValue)") } didSet { // after change print("Changed: \(score - oldValue)") } } init(_ name: String,_ score: Int){ self.name = name self.score = score } } let tom = User("tom", 23) tom.score = 53 tom.score = 40
method
class User { let name: String // property var score: Int init(_ name: String,_ score: Int){ self.name = name self.score = score } // クラスに紐付いた関数はメソッド func sayHi(msg: String){ print("\(msg) \(name)") } } let tom = User("tom", 23) // tom.sayHi() tom.sayHi(msg: "hola")
classの継承
class User { let name: String // property var score: Int init(_ name: String,_ score: Int){ self.name = name self.score = score } func sayHi(){ print("hi \(name)") } } class AdminUser: User { func sayHello(){ print("hello \(name)") } override func sayHi(){ print("[admin] hi \(name)") } } let tom = User("tom", 23) let bob = AdminUser("bob", 33) print(bob.name) print(bob.score) bob.sayHi() bob.sayHello()
class User { let name: String // property var score: Int static var count = 0 init(_ name: String,_ score: Int){ self.name = name self.score = score User.count += 1 } func sayHi(){ print("hi \(name)") } static func getInfo(){ print("\(count) instances") } } User.getInfo() let tom = User("tom", 23) User.getInfo()
型キャスト
// asを使った変換 -> 型キャスト class User { let name: String // property init(_ name: String){ self.name = name } } class AdminUser: User {} let tom = User("tom") let bob = AdminUser("bob") let users: [User] = [tom, bob] for user in users { // if let u = user as? AdminUser{ // print(u.name) // } if user is AdminUser { user as! AdminUser print(u.name) } }