구조체

JG Ahn·2024년 10월 7일

swift 기초

목록 보기
11/23
post-thumbnail

1. 구조체란?

  • 구조체는 값(value)타입
  • 타입이름은 대문자 카멜케이스
  • 메소드에서 프로퍼티 변경시 "mutating" 키워드 사용

2. 구조체 문법

  • 구조체 정의 : "struct" 키워드 사용
struct 이름{
	/* 
    구현부 
    
    [Memberwise Initializer]
    클래스와 달리 init을 정의하지 않아도 모든 프로퍼티 초기화를 자동 생성해주는 기능
    */
}
  • 구조체 프로퍼티 및 메서드 구현
struct Sample {
	// 가변 프로퍼티
	var mutableProperty: Int = 100
    
    // 불변 프로퍼티
    var immutableProperty: Int = 100
    
    // 타입 프로퍼티(static 키워드 사용. 해당 구조체 타입 전체가 사용하는 프로퍼티)
    static var typeProperty: Int = 100
    
    // 인스턴스 메소드
    func instanceMethod() {
    	print("instance method")
    }
    
    // 타입 메소드(static 키워드 사용. 해당 구조체 타입 전체가 사용하는 메소드)
    static func typeMethod() {
    	print("typeMethod")
    }
    
    // 메소드에서 프로퍼티 변경 : mutating 키워드 사용
    mutating func propertyChange() {
        mutableProperty += 1
        print(mutableProperty)
    }
}
  • 구조체 사용
// 가변 인스턴스 생성
var mutable: Sample = Sample()

mutable.mutableProperty = 150

// 불변 인스턴스 생성 - 불변 인스턴스는 가변 프로퍼티도 수정 불가
let immutable: Sample = Sample()

// 타입 프로퍼티 및 메소드 - 인스턴스는 사용 불가
Sample.typeProperty = 400
Sample.typeMethod()

// 메소드를 사용해 프로퍼티 변경(mutating)
mutable.propertyChange() //결과 : 151

Memberwise Initializer

  • 구조체가 자동으로 제공하는 초기화 메서드(class는 제공되지 않음)

예시) init(name: String, age: Int)라는 생성자를 만들지 않았지만 자동으로 제공됨

struct User {
    var name: String
    var age: Int
}

// Memberwise Initializer 자동 제공
let user = User(name: "Alice", age: 25)

print(user.name) // Alice
print(user.age)  // 25
  • Memberwise Initializer가 제공되는 경우
    • 구조체의 모든 프로퍼티가 기본값이 없을때
    • 사용자가 별도의 init을 정의하지 않았을 때 제공

0개의 댓글