Swift 문법 - 구조체(Struct)

eelijus·2023년 2월 6일
0

Swift Syntax

목록 보기
11/11

💡구조체

https://docs.swift.org/swift-book/LanguageGuide/ClassesAndStructures.html

구조체 (Structure)

구조체는 값 타입이다. 스위프트의 타입은 대부분 구조체로 이루어져있음.

  • 구조체 생성 - 프로퍼티 및 메서드 구현
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()
profile
sujileelea

0개의 댓글