iOS_Swift/문법 정리
Swift - 클래스 property와 method
chozjjae
2022. 2. 6. 21:25
클래스(class)안에 property와 method를 생성하는 방법을 알아보겠습니다.
class의 용어정리 - https://chozjjae.tistory.com/43
class [클래스 이름] : [부모 클래스] {
[프로퍼티]
[인스턴스 메서드]
[타입(type) 메서드(클래스 메서드)]
}
//기본 틀
Property 추가하기
클래스 내부에 프로퍼티를 추가할때는 반드시
1. 초기값이 있거나
2. init메서드를 이용하여 인스턴스를 초기화 시켜주거나
3. 옵셔널 변수(상수)를 이용하여 선언해 주어야 합니다.
property는 저장 프로퍼티(stored property)와 계산 프로퍼티(calculated property) 두 종류로 나눠집니다.
일반적으로 아래방법처럼 사용한다면 저장 프로퍼티(stored property)로 사용됩니다.
class hap{
var x : Int = 10
var y : Int = 20
} //방법 1
class gop{
var a : Int?
var b : Int!
} //방법 3
Method 추가하기
인스턴스(instance) 메서드
일반적인 메서드는 인스턴스(instance)메서드 라고 한다.
class hap{
var x : Int = 10
var y : Int = 20
func math(){ //인스턴스 메서드
print("값1 = \(x), 값2 = \(y)")
}
}
클래스(class) or 타입(type) 메서드
인스턴스 메서드와 동일한 방법으로 선언하지만 class나 static 키워드를 앞에 붙여서 선언합니다.
class키워드로 만든 클래스메서드는 자식 클래스에서 override가 가능합니다.
class hap{
var x : Int = 10
var y : Int = 20
func math(){
print("값1 = \(x), 값2 = \(y)")
}
class func math1(){
print("math1은 클래스 메서드 입니다.")
}
static func math2(){
print("math2은 클래스 메서드 입니다.")
}
}
var cho : hap = hap()
cho.math()
print(cho.x)
//10
hap.math1()
//math1은 클래스 메서드 입니다.
hap.math2()
//math2은 클래스 메서드 입니다.
참고 영상 : https://www.youtube.com/watch?v=OBRQ5l4xLZo&list=PLJqaIeuL7nuEEROQDRcy4XxC9gU6SYYXb&index=22
https://www.youtube.com/watch?v=NlyQAXTXpW8&list=PLJqaIeuL7nuEEROQDRcy4XxC9gU6SYYXb&index=24