[Swift 문법] 구조체

!·2022년 6월 25일
0

Swift 문법

목록 보기
10/27

구조체 프로퍼티 및 메소드

  • 프로퍼티는 cpp에서의 멤버변수, java에서의 필드와 비슷한 개념이다.
  • 메소드는 cpp에서의 멤버함수, java에서 메소드와 비슷한 개념이다.
struct Sample{
	var mutableProperty: Int = 100 // 가변 프로퍼티
    let imutableProperty : Int = 100 // 불변 프로퍼티
    static var typeProperty : Int = 100 // 타입 프로퍼티
    
    // 인스턴스 메소드
    func instanceMethod(){
    	print("instanceMethod()")
    }
    
    // 타입 메소드
    static func typeMethod(){
    	print("typeMethod()")
    }
}

구조체 사용

var mutable : Sample = Sample()

mutable.mutableProperty = 200
mutable.immutableProperty = 200 // 불변 프로퍼티로, 컴파일 에러 발생

let immutable : Sample = Sample()

immutable.mutableProperty = 200 // 불변 인스턴스 객체로, 컴파일 에러 발생
immutable.immutableProperty = 200 // 불변 인스턴스 객체로, 컴파일 에러 발생

Sample.typeProperty = 200
Sample.typeMethod()

mutable.typeProperty = 200 // 타입 프로퍼티는 반드시 타입명.프로퍼티로 접근해야한다.
mutable.typeMethod() // 타입 메소드는 반드시 타입명.메소드로 접근해야한다.
profile
개발자 지망생

0개의 댓글