티스토리 뷰
클래스와 구조체 비교
공통점
- 값을 저장하기 위한 프로퍼티 정의 가능
- 기능을 제공하기 위한 함수 정의 가능
- subscript 문법을 이용해 특정 값에 접근하기 위한 subscript 정의 가능
- 초기 상태를 설정할 수 있는 initializer 정의 가능(단 struct는 기본 제공하나 class는 기본 제공하지 않음)
- 기본 구현에서 기능 확장 가능
- 표준 기능을 제공하기 위한 프로토콜 채택(conform) 가능
차이점(클래스만 가능)
- 상속
- 타입캐스팅
- Deinitializer
- Reference counting
구조체와 열거형은 값타입
구조체
struct Student { var name: String var age: Int } let student = Student(name: "홍길동", age: 23) print(student) //Student(name: "홍길동", age: 23) var copyStudent = student copyStudent.name = "박길동" print(student) //Student(name: "홍길동", age: 23)열
열거형
enum Move: String { case up = "Up" case down = "Down" case left = "Left" case right = "Right" } var currentMove = Move.up print(currentMove.rawValue) //Up var rememberMove = currentMove currentMove = .right print(currentMove.rawValue) //Right print(rememberMove.rawValue) //Up
클래스는 참조타입
class CStudent {
var name = ""
var age = 0
}
let cStudent = CStudent()
cStudent.name = "홍길동"
cStudent.age = 23
print(cStudent.name) //홍길동
print(cStudent.age) //23
let copyCStudent = cStudent
copyCStudent.name = "박홍길동"
copyCStudent.age = 25
print(cStudent.name) //박홍길동
print(cStudent.age) //25
이런 결과가 나온 이유는
"let copyCStudent = cStudent" 에서 copyCStudent가 cStudent 인스턴스를 복사한 것이 아니라 참조한 것이기 때문
copyCStudent 와 cStudent가 가리키는 메모리 주소가 동일
copyCStudent를 상수로 선언했지만 copyCStudent 자체를 바꾸는 것이 아니라 그것이 참조하는 값을 변경하는 것이기 때문에 가능
식별연산자(Identity Operators)
- === : 두 상수나 변수가 같은 인스턴스를 참조하고 있는 경우 참
- !== : 두 상수나 변수가 다른 인스턴스를 참조하고 있는 경우 참
if copyCStudent === cStudent {
print("cStudent and copyCStudent is Equal") // 이 부분이 출력
}
다음 시간엔 언제 클래스를 쓰고 언제 구조체를 선택해야되는지에 대해서 알아봅시다.
'Swift&IOS' 카테고리의 다른 글
type(of: ) (0) | 2019.09.04 |
---|---|
Swift로 간단하게 화씨를 섭씨로, 섭씨를 화씨로 변환해보자 (0) | 2019.08.29 |
Frame VS Bounds (0) | 2019.08.23 |
UISearchController (1) | 2019.07.04 |
PageViewController 만들어보기. (0) | 2019.07.01 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- programmers
- SwiftUI
- CombineLatest
- 알고리즘
- 삨
- compactMap
- SEQUENCE
- swift
- 결합연산자
- 스위프트유아이
- AutoLayout
- combine
- Queue
- Apple
- ErrorHandling
- 스택뷰
- iOSCombine
- 스유
- 현업이그리운
- replaceNil
- 스위프트
- ios
- 콤바인
- MVC
- 텔큐온
- BBIK
- UIViewControllerRepresentable
- 자료구조
- Just
- 유니온파인드
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 | 29 |
30 | 31 |
글 보관함