💡구조체
https://docs.swift.org/swift-book/LanguageGuide/ClassesAndStructures.html
구조체는 값 타입이다. 스위프트의 타입은 대부분 구조체로 이루어져있음.
struct Sample {
//가변 프로퍼티
var mutableProperty: Int = 1
//불변 프로퍼티
let immutableProperty: Int = 1
//타입 프로퍼티
static var typeProperty: Int = 1
//인스턴스 메서드
func instanceMethod() {
print("instance method")
}
//타입 메서드
static func typeMethod() {
print("type method")
}
}
import Foundation
//깂 type Sample. 이제 Sample이라는 타입이 생겼다.
struct Sample {
//가변 프로퍼티
var mutableProperty: Int = 1
//불변 프로퍼티
let immutableProperty: Int = 1
//타입 프로퍼티
static var typeProperty: Int = 1
//인스턴스 메서드
func instanceMethod() {
print("instance method")
}
//타입 메서드
static func typeMethod() {
print("type method")
}
}
//가변인스턴스 생성
var mutableInstance: Sample = Sample()
//가변 프로퍼티값 변경
mutableInstance.mutableProperty = 0
//불변 프로퍼티값 변경 -> 불변 프로퍼티는 인스턴스 생성 후 변경 불가능
//컴파일 오류 발생
mutableInstance.immutableProperty = 0
//불변 인스턴스 생성
let immutableInstance: Sample = Sample()
//가변 프로퍼티라도 불변 인스턴스일 경우 생성 후 변경 불가능
//컴파일 오류 발생
immutableInstance.mutableProperty = 0
//아래는 뭐
immutableInstance.immutableProperty = 0
//타입 프로퍼티 및 메서드
Sample.typeProperty = 0
Sample.typeMethod()
//OUTPUT : type method
//인스턴스에서는 타입 프로퍼티나 타입 메서드 사용 불가능
//컴파일 오류 발생
mutableInstance.typeProperty = 0
mutableInstance.typeMethod()
import Foundation
struct Student {
var name: String = "student's name"
//키워드도 ``로 감싸주면 이름으로 사용할 수 있다 와웅
var `class`: String = "class's name"
static func selfIntroduce() {
print ("학생 타입 입니다.")
}
//self는 인스턴스 자신을 지칭한다.
func selfIntroduce() {
print("나는 \(self.class)의 \(self.name)이다.")
}
}
Student.selfIntroduce()
var sujilee: Student = Student()
sujilee.selfIntroduce()
sujilee.name = "sujilee"
sujilee.class = "iOS"
sujilee.selfIntroduce()
//불변 인스터의 프로퍼티값을 설정해주기위해 이니셜라이저 사용
let lealee: Student = Student(name: "lealee", class: "iOS")
lealee.selfIntroduce()