카테고리 없음
Swift) class
나태한개발
2024. 6. 16. 19:43
클래스 정의
클래스를 정의하려면 class 키워드를 사용한다. 클래스는 속성(Property)과 메서드(Method)를 가질 수 있다.
class Person {
var name: String
var age: Int
init(name: String, age: Int) {
self.name = name
self.age = age
}
func greet() {
print("Hello, my name is \(name) and I am \(age) years old.")
}
}
위 예제에서 Person 클래스는 name과 age라는 두 개의 속성을 가지고 있으며, greet라는 메서드를 정의하고 있다. init 메서드는 클래스의 인스턴스를 초기화하는 생성자이다.
클래스 인스턴스 생성 및 사용
클래스의 인스턴스를 생성하려면 init 메서드를 호출하여 초기화한다.
let person = Person(name: "John", age: 30)
person.greet() // 출력: Hello, my name is John and I am 30 years old.
클래스의 상속
스위프트에서 클래스는 상속을 통해 다른 클래스를 기반으로 새로운 클래스를 정의할 수 있다. 상속받은 클래스는 부모 클래스의 속성과 메서드를 상속받는다.
class Employee: Person {
var jobTitle: String
init(name: String, age: Int, jobTitle: String) {
self.jobTitle = jobTitle
super.init(name: name, age: age)
}
override func greet() {
print("Hello, my name is \(name), I am \(age) years old and I work as a \(jobTitle).")
}
}
let employee = Employee(name: "Jane", age: 28, jobTitle: "Engineer")
employee.greet() // 출력: Hello, my name is Jane, I am 28 years old and I work as a Engineer.
클래스와 구조체의 차이점
스위프트에서 클래스와 구조체는 많은 공통점을 가지지만, 몇 가지 중요한 차이점이 있다.
- 클래스는 참조 타입(reference type)이고, 구조체는 값 타입(value type)이다.
- 클래스는 상속을 지원하지만, 구조체는 상속을 지원하지 않는다.
- 클래스는 디이니셜라이저(deinitializer)를 가질 수 있지만, 구조체는 가질 수 없다.
struct PersonStruct {
var name: String
var age: Int
}
var person1 = PersonStruct(name: "Alice", age: 25)
var person2 = person1
person2.name = "Bob"
print(person1.name) // 출력: Alice
print(person2.name) // 출력: Bob
class PersonClass {
var name: String
var age: Int
init(name: String, age: Int) {
self.name = name
self.age = age
}
}
let person3 = PersonClass(name: "Alice", age: 25)
let person4 = person3
person4.name = "Bob"
print(person3.name) // 출력: Bob
print(person4.name) // 출력: Bob
타입 메서드와 타입 속성
클래스는 인스턴스와 관계없이 사용할 수 있는 타입 메서드와 타입 속성을 정의할 수 있다. 이를 위해 static 키워드를 사용한다. 서브클래스에서 오버라이드 가능하게 하려면 class 키워드를 사용한다.
class Math {
static let pi = 3.14159
static func square(_ number: Double) -> Double {
return number * number
}
class func cube(_ number: Double) -> Double {
return number * number * number
}
}
print(Math.pi) // 출력: 3.14159
print(Math.square(2)) // 출력: 4.0
print(Math.cube(2)) // 출력: 8.0
초기화 위임
클래스는 다른 초기화 메서드에게 초기화를 위임할 수 있다. 이를 통해 초기화 코드를 재사용하고 간결하게 작성할 수 있다.
class Vehicle {
var currentSpeed = 0.0
init() {}
init(currentSpeed: Double) {
self.currentSpeed = currentSpeed
}
}
class Car: Vehicle {
var gear = 1
init(currentSpeed: Double, gear: Int) {
self.gear = gear
super.init(currentSpeed: currentSpeed)
}
override init(currentSpeed: Double) {
super.init(currentSpeed: currentSpeed)
self.gear = 3
}
}
디이니셜라이저
클래스는 디이니셜라이저를 정의하여 인스턴스가 해제될 때 수행할 작업을 지정할 수 있다. deinit 키워드를 사용하여 디이니셜라이저를 정의한다.
class BankAccount {
var balance: Double
init(balance: Double) {
self.balance = balance
print("계좌가 생성되었습니다. 잔액: \(balance)")
}
deinit {
print("계좌가 해제되었습니다. 잔액: \(balance)")
}
}
var account: BankAccount? = BankAccount(balance: 1000.0)
account = nil // 출력: 계좌가 해제되었습니다. 잔액: 1000.0