Swift 구조체(2020.10.29)

K S Michael·2020년 10월 29일

swift TIL

목록 보기
6/29

swift 구조체는 타입을 정의하는 곳이기 때문에 대문자 카멜케이스를 사용한다.

구조체 정의

struct 이름 {
구현부
}

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  // 구조체 정의에서 var 키워드 선언으로 수정 가능
//mutable.immutableProperty = 200 // 구조체 정의에서 let 키워드 선언으로 수정 불가

// 불변 인스턴스
let immutable: Sample = Sample() // let 으로 선언한 불변 인스턴스

//mutable.mutableProperty = 200  // 프로퍼티를 var 로 선언 해도 인스턴스가 let 이기 때문에 수정 불가 ( class 에서는 변경 가능 )

//mutable.immutableProperty = 200 // 프로퍼티 let로 선언 인스턴스 let ==> 무조건 수정 불가

// 타입 프로퍼티 및 메서드
Sample.typeProperty = 300  // Sample 라는 타입에서 "만" 접근 가능한 프로퍼티다
Sample.typeMethod() //type method 

// mutable.typeProperty = 400 // 인스턴스에서는 static에 접근할수 없다.
// mutable.typeMethod()
  • 학생 구조체

var로 선언한 인스턴스에서 var 로 선언한 프로퍼티 ...

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"
jina.selfIntroduce() // 저는 Swift반 unKnown입니다.

// let 선언 인스턴스는 프로퍼티를 변경이 불가능하지만 호출은 가능하다!


출처 : 유튜브 "yagom"

profile
차근차근

0개의 댓글