swift
[swift] 구조체 (struct)
domisolll
2020. 6. 22. 17:09
구조체 (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
// mutable.immutableProperty = 200 -> let으로 선언했기 때문에 변경 불가
let immutable: Sample = Sample()
// immutable.mutableProperty = 200 -> immutable 을 let으로 선언했기 때문에 변경 불가
Sample.typeProperty = 300
Sample.typeMethod()
// 인스턴스에서 이 타입 프로퍼티나 메소드를 사용하고자 하는 것은 불가능
// mutable.typeProperty = 400
// mutable.typeMethod()
타입 프로퍼티/메소드 ?
타입 자체가 사용할 수 있는 프로퍼티 ➡️ 프로퍼티를 타입 자체와 연결함
인스턴스의 생성 여부와 관련 없이 타입 프로퍼티의 값은 하나이다.
타입 프로퍼티는 선언할 때 인스턴스 프로퍼티와는 다르게 기본값을 줘야 함
그 타입의 모든 인스턴스가 공통으로 사용하는 값, 또는 모든 인스턴스에서 공용으로 접근하고 값을 변경할 수 있는 변수 등을 정의할 때 유용하다.
struct Student {
var name: String = "unknown"
var `class`: String = "Swift"
static func selfIndtoduce() {
print("student type")
}
func selfIntroduce() {
print("My name is \(name) in \(self.class) class")
}
}
Student.selfIndtoduce() // "student type"
var misol: Student = Student()
misol.name = "misol"
misol.class = "swift"
misol.selfIntroduce() // "My name is misol in swift class"
[Swift] 프로퍼티(Property) - jinShine
프로퍼티(Property) 1. 프로퍼티 프로퍼티는 크게 5가지가 존재합니다. 저장 프로퍼티(Stored Properties) 지연 저장 프로퍼티(Lazy Stroed Properties) 연산 프로퍼티(Computed Properties) 프로퍼티 감시자(Property Obs
jinshine.github.io
[LECTURE] 13. 구조체 (💎생각해보기) : edwith
생각해보기 ▶다른 프로그래밍 언어를 배워본 적이 있다면, 내가 알고있는 언어의 구조체와 스위프트의 구조체와 어떤점 이 다른지 비교해봅시다~! +)다른 수강생들과 자유롭게 토... - 부스
www.edwith.org