
프로퍼티에 대해 먼저 알아보겠습니다.
프로퍼티(Property)는 객체지향 프로그래밍에서 클래스나 구조체의 속성을 정의하는 데 사용되는 변수를 의미합니다. 프로퍼티는 객체의 상태를 나타내며, 해당 객체가 가지고 있는 데이터를 저장하는 역할을 합니다.
struct Person {
var name: String // 가변 프로퍼티
let age: Int // 불변 프로퍼티
}
var person = Person(name: "Alice", age: 30)
person.name = "Bob" // 가변 프로퍼티는 수정 가능
// person.age = 31 // 불변 프로퍼티는 수정 불가
import UIKit
// MARK: - 구조체 정의
struct Sample {
var mutableProperty: Int = 100 // 가변 프로퍼티
let immutableProperty: Int = 100 // 불변 프로퍼티
static var typeProperty: Int = 100 // 타입 프로퍼티
// 인스턴스 메서드
func instanceMethod() {
print("instance Method")
}
// 타입 메서드
static func typeMethod() {
print("type Method")
}
}
// MARK: - 구조체 사용
// 가변 인스턴스
var mutable: Sample = Sample()
mutable.mutableProperty = 200 // 가변 프로퍼티는 수정 가능
//mutable.immutableProperty = 200 // 불변 프로퍼티는 수정 불가
// 불변 인스턴스
let immutable: Sample = Sample()
//immutable.mutableProperty = 200 // 불변 인스턴스는 수정 불가
//immutable.immutableProperty = 200 // 불변 인스턴스는 수정 불가
// 타입 프로퍼티 및 메서드 사용
Sample.typeProperty = 300
Sample.typeMethod() // "type Method" 출력
// MARK: - 학생 구조체
struct Student {
var name: String = "unknown"
var `class`: String = "Swift"
static func selfIntroduce() {
print("학생타입입니다.")
}
func selfIntroduce() {
print("저는 \(self.class) 반 \(name)입니다.")
}
}
Student.selfIntroduce() // "학생타입입니다." 출력
var geuni: Student = Student()
geuni.name = "geuni"
geuni.class = "Swift"
geuni.selfIntroduce() // "저는 Swift 반 geuni입니다." 출력
let jina: Student = Student()
// 불변 인스턴스이므로 프로퍼티 값 변경 불가
// 컴파일 오류 발생
// jina.name = "jina"
jina.selfIntroduce() // "저는 Swift 반 unknown입니다." 출력
import UIKit
// MARK: - 클래스 정의
class Sample {
var mutableProperty: Int = 100 // 가변 프로퍼티
let immutableProperty: Int = 100 // 불변 프로퍼티
static var typeProperty: Int = 100 // 타입 프로퍼티
// 인스턴스 메서드
func instanceMethod() {
print("instance method")
}
// 타입 메서드
// 재정의 불가 타입 메서드 - static
static func typeMethod() {
print("type method - static")
}
// 재정의 가능 타입 메서드 - class
class func classMethod() {
print("type method - class")
}
}
// MARK: - 클래스 사용
var mutableReference: Sample = Sample()
mutableReference.mutableProperty = 200 // 가변 프로퍼티 수정 가능
//mutableReference.immutableProperty = 200 // 불변 프로퍼티 수정 불가
let immutableReference: Sample = Sample()
//immutableReference.mutableProperty = 200 // 불변 인스턴스는 수정 불가
//immutableReference.immutableProperty = 200 // 불변 인스턴스는 수정 불가
// 타입 프로퍼티 및 메서드 사용
Sample.typeProperty = 300
Sample.classMethod() // "type method - class" 출력
// MARK: - 학생 클래스
class Student {
var name: String = "unknown"
var `class`: String = "Swift"
class func selfIntroduce() {
print("학생타입입니다.")
}
func selfIntroduce() {
print("저는 \(self.class) 반 \(name)입니다.")
}
}
Student.selfIntroduce() // "학생타입입니다." 출력
var geuni: Student = Student()
geuni.name = "geuni"
geuni.class = "Swift"
geuni.selfIntroduce() // "저는 Swift 반 geuni입니다." 출력
let jina: Student = Student()
jina.name = "jina"
jina.selfIntroduce() // "저는 Swift 반 jina입니다." 출력