[Swift 문법] 클래스

!·2022년 6월 25일
0

Swift 문법

목록 보기
11/27

클래스

  • 구조체는 값 타입인 반면에, 클래스는 참조 타입이다.
  • swift에서 클래스다중상속을 지원하지 않는다.
  • 전체적으로 구조체와 매우 동일하지만, 2가지 종류의 타입메소드가 존재한다.
  • static 타입메소드는 하위 클래스에서 재정의가 불가능한 메소드이다.
  • class 타입메소드는 하위 클래스에서 재정의가 가능한 메소드이다.
  • 구조체와의 차이점은 let으로 인스턴스를 생성하였을때, 클래스가변 프로퍼티의 값의 변경이 가능하다는 점이다.
class Sample{
	var mutableProperty : Int = 100	// 가변 프로퍼티
    let immutableProperty : Int = 200 // 불변 프로퍼티
    static var typeProperty :Int = 100 // 가변 타입 프로퍼티
    static let immutbaleTypeProperty : Int = 100 // 불변 타입 프로퍼티 
    
    func instanceMethod(){
    	print("instanceMethod()")
    }
    
    // 타입 메소드
    // 재정의 불가 타입 메소드 - static 
    static func typeMethod(){
    	print("typeMethod - static")
    }
    
    // 재정의 가능 타입 메소드 - class
    class func classMethod(){
    	print("classMethod - class")
    }
}

var sampleInstance: Sample = Sample(mutableProperty: 3, imuutableProperty: 2 ....)

클래스 인스턴스 소멸

  • 클래스 인스턴스 소멸 메소드는 deinit 이며, 이를 정의할때는 타입명, 매개변수가 필요없다.
  • 인스턴스가 소멸될때 자동으로 호출된다.
class Person{
	var name: String
    var age: age
    
    deinit{
    	print("소멸")
    }
}

var person: Person? = Person(name: "이준혁", age: 25)
person = nil // "소멸" 출력

식별연산자

  • 구조체와 다르게 클래스는 값이 아닌 참조타입이다.
  • 동일한 인스턴스를 참조하는지 식별연산자 === 를 통해 알 수 있다.
class Person{
	let name: String 
    let age: Int
}
var person1 = Person(name: "이준혁", age: 25)
var person2 = person1
var person3 = Person(name: "이준혁", age: 25)

let person1&person2 = person1 === person2 // true
let person1&person3 = person1 === person3 // false
let person2&person3 = person2 === person3 // false
profile
개발자 지망생

0개의 댓글