[Swift] Class
Property
need the initial value.
- initial value
- Initialize to init
- optional variable, constant
// 1.
class Man {
var age: Int = 0
var weight: Double = 0.0
}
// 2.
class Man {
var age: Int?
var weight: Double!
}
// 3.
class Man {
var age: Int = 1
var weight: Double = 3.5
func display() {
print("Age=\(age), Weight=\(weight)")
}
}
var kim = Man()
kim.display()
Class or Type method
class Man {
var age: Int = 1
var weight: Double = 3.5
func display() {
print("Age = \(age), Weight = \(weight)")
}
class func cM() {
print("cM is class method")
}
static func scM() {
print("scM is class method(static)")
}
}
var kim = Man()
kim.display()
Man.cM()
Man.scM()
Class methods created with class keywords can be overridden by child classe
init()
- constructor
int() {
}
class Man {
var age: Int = 1
var weight: Double = 3.5
func display() {
print("Age = \(age), Weight = \(weight)")
}
init(yourAge: Int, yourWeight: Double) {
age = yourAge
weight = yourWeight
} // designated initializer
}
var kim = Man(yourAge: 10, yourWeight: 10.5)
kim.display()
Self
class Man {
var age: Int
var weight: Double
func display() {
print("Age = \(age), Weight = \(weight)")
}
init(age: Int, weight: Double) {
self.age = age
self.weight = weight
} // designated initializer
}
var kim = Man(age: 10, weight: 10.5)
kim.display()
Stored property and Computed property
class Man {
var age: Int = 1 // stored property
var weight: Double = 3.5 // stored property
var koreanAge: Int { // computed property
get {
return age + 1
}
}
func display() {
print("Age = \(age), Weight = \(weight)")
}
init(age: Int, weight: Double) {
self.age = age
self.weight = weight
} // designated initializer
}
var kim = Man(age: 10, weight: 20.5)
print(kim.koreanAge)
Getter
- If there is no setter, get{} can be omitted.
class Man {
var age: Int = 1
var koreanAge: Int {
get {
return age + 1
}
}
class Man {
var age: Int = 1
var koreanAge: Int {
return age + 1
}
}
Setter
class Man {
var age: Int = 1
var weight: Double = 3.5
var koreanAge: Int {
get {
return age + 1
}
set(internationalAge) {
age = internationalAge + 1
}
}
func display() {
print("Age = \(age), Weight = \(weight)")
}
init(age: Int, weight: Double) {
self.age = age
self.weight = weight
} // designated initializer
}
var kim = Man(age: 10, weight: 20.5)
print(kim.koreanAge) // 11, call getter
kim.koreanAge = 2 // call setter
print(kim.age) // 3
- newValue
class Man {
var age: Int = 1
var weight: Double = 3.5
var koreanAge: Int {
get { return age + 1 }
set { age = newValue + 1 } // Shorthand Setter Declaration
}
}
Method overloading
class Man {
var age: Int = 1
var weight: Double = 3.5
func display() {
print("Age = \(age), Weight = \(weight)")
}
init(age: Int, weight: Double) { // 1
self.age = age
self.weight = weight
}
init(age: Int) { // 2
self.age = age
}
}
var kim : Man = Man(age: 10, weight: 20.5) // 1
var kim2 : Man = Man(age: 30) // 2
kim.display()
kim2.display()