App/iOS

[Swift][언어공부] 구조체, 클래스

앙두딘 2022. 7. 6. 16:35

구조체

대부분의 타입이 구조체로 이루어져있음

struct 키워드 사용

struct Sample{
	//인스턴스 프로퍼티
	var mutableProperty: Int = 100 //가변 프로퍼티
	let immutableProperty: Int = 10 //불변 프로퍼티

	// 타입 프로퍼티: 
	//Sample.typeProperty처럼 타입으로 호출가능
	static var typeProperty: Int = 100 
	
	//인스턴스 메서드
	func instanceMethod(){
		print("instance method")
	}

	//타입 메서드
	static func typeMethod(){
		print("type method")
	}
}

가변인스턴스 → 프로퍼티 값 변경 가능(불변프로퍼티는 불가능)

불변 인스턴스 → 프로퍼티 값 변경 불가능(가변 프로퍼티일지라도)

타입프로퍼티, 타입메소드는 인스턴스로 접근할 수 없음

var instance = Sample()
instance.typeProperty = 100 //Error
instance.typeMethod() //Error

//타입으로 호출해줘야 함
Sample.typeProperty = 100
Sample.typeMethod()

클래스

구조체와 매우 유사

구조체는 값 타입, 클래스는 참조 타입이라는 차이가 있다.

스위프트의 클래스: 다중 상속이 되지 않음

다른건 구조체와 유사하지만, 타입메소드는 종류가 두 가지가 있음

타입 메소드 종류

  • static
//재정의 불가능 타입 메소드
static func typeMethod(){
	print("type method - static")
}
  • class
//재정의 가능 타입 메소드
class func classMethod(){
	print("type method - class")
}
var mutableReference: Sample = Sample()
mutableReference.mutableProperty = 200
mutableReference.immutableProperty = 200 //Error

let immutableReference: Sample = Sample()
//불변객체여도 var프로퍼티 수정할 수 있음!
immutableReference.mutableProperty = 200 
immutableReference.immutableProperty = 200 //Error

'App > iOS' 카테고리의 다른 글

[Swift][언어공부] Swift 기초  (0) 2022.07.06