Swift/기초 문법
구조체
수줌이
2021. 2. 10. 11:20
⭐ 구조체 ?
-
스위프트 대부분 타입은 구조체로 이루어져 있습니다.
-
구조체는 값(value) 타입입니다.
-
타입이름은 대문자 카멜케이스를 사용하여 정의합니다.
1. 구조체 문법
-
정의 : "struct" 키워드 사용
struct 이름 {
/* 구현부 */
}
2. 프로퍼티 및 메서드
-
프로퍼티 : (타입 내) 인스턴스 변수
-
메서드 : (타입 내) 함수
struct Sample {
var mutuableProperty: Int = 100 // 가변 프로퍼티
let immutableProperty: Int = 100 // 불변 프로퍼티
// ----이상 인스턴스 프로퍼티----
static var typeProperty: Int = 100 // 타입안에서만 사용 가능한 타입 프로퍼티
// 인스턴스 메서드
func instanceMethod() {
print("instance method")
}
// 타입 메서드
static func typeMethod() {
print("type method")
}
}
3. 구조체 사용
// 가변 인스턴스
var mutable: Sample = Sample()
mutable.mutableProperty = 200
mutable.immutableProperty = 200 // error
// 왜? immutableProperty를 구조체 내에서 let으로 선언
// 불변 인스턴스
let immutable: Sample = Sample()
// 불변 인스턴스는 아무리 가변 프로퍼티라도
// 인스턴스 생성 후에 수정할 수 없습니다
// 컴파일 오류 발생
//immutable.mutableProperty = 200
//immutable.immutableProperty = 200
// 타입만 사용 가능한 타입 프로퍼티 및 메서드
Sample.typeProperty = 300
Sample.typeMethod() // 출력:type method
mutable.typeProperty = 400 //error -> 'mutable'이 타입 프로퍼티가 아니어서
mutable.typeMethod() //error -> 'mutable'이 타입 프로퍼티가 아니어서
4. 학생 구조체 만들어 보기
struct Student {
var name: String = "unknown"
var 'class': String = "Swift" // class가 키워드라서 변수로 사용하기 위해 ''로 묶어줌
static func selfIntroduce() {
print("학생 타입입니다")
}
func selfIntroduce() {
print("저는 \(self.class)반 \(name)입니다")
}
}
Student.selfIntroduce() // 학생타입입니다
var yagom: Student = Student()
yagom.name = "yagom"
yagom.class = "스위프트"
yagom.selfIntroduce() // 저는 스위프트반 yagom입니다
let jina: Student = Student()
jina.name = "jina" //error
// 불변 인스턴스이므로 프로퍼티 값 변경 불가
// 컴파일 오류 발생
jina.selfIntroduce() // 저는 Swift반 unknown입니다
이 글은 Boostcourse에서 배운 내용을 정리하여 작성하였습니다.