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
예시) 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