Struct: 구조체

Terry/이은한·2023년 1월 12일
1

SWIFT

목록 보기
2/4

본 블로그의 내용은 몇몇 학습 기관들의 자료를 참고하여 저자 스스로 학습한 내용이기에 틀린 내용이 포함되어 있을 수 있습니다. 오류를 발견하실 경우 댓글을 남겨주시기를 부탁드립니다. 🙏🏻

정의문법


struct Name {
	/* 구현부 */
    }
    

property, method

  • property
    - mutableProperty
    var name: type = value
    - immutableProperty
    let name: type = value
    - typeProperty
    static var name: type = value
    다른 인스턴스에서 사용 불가
  • method
    - instanceMethod
    func name() {
    구현부
    }
    - typeMethod
    static func name() {
    구현부
    }
    다른 인스턴스에서 사용 불가

Instance

구조체 단위

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")
    }
}


// 가변 인스턴스 생성
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

// 인스턴스에서는 타입 프로퍼티나 타입 메서드를
// 사용할 수 없습니다
// 컴파일 오류 발생
//mutable.typeProperty = 400
//mutable.typeMethod()

referance
https://yagom.github.io/swift_basic/contents/08_struct/

profile
iOS 개발자

0개의 댓글