라벨이 struct인 게시물 표시

[swift] 구조체(struct)와 클래스(class)의 비교

이미지
[swift] 구조체(struct)와 클래스(class) 구조체와 클래스는 코드블럭을 만들 때 쓰이고 그 문법 또한 매우 닮았다. 하지만 다른점이 있기 때문에 그 특성을 잘 파악하고, 필요한 부분에서 활용할 수 있도록 정리한다. 정의 방법 (Definition) 구조체는 struct , 클래스는 class 라는 키워드를 사용하여 정의한다. struct Student{ // properties and methods } class Student { // properties and methods } 프로퍼티와 메소드 (Properties and Methods) 이 예제에서는 학생의 구조체와 클래스의 정의 예제이다. SomeStudent struct 와 AnotherStudent class 모두 firstName, lastName, grade라는 properties를 가지고 grade를 출력해주는 printGrade() 메소드를 가진다. 다른 점은 클래스에서는 init() 함수를 따로 정의 해줘야 한다. struct SomeStudent{ // properties let firstName: String let lastName: String var grade: Int // methods func printGrade(){ print("grade is \(grade)") } } class AnotherStudent { // properties let firstName: String let lastName: String var grade: Int // methods init(firstName: String, lastName: String, grade: Int){ self.firstName = firstName self.lastName = lastName self.grade = grade } func printGrade