-
[Stanford Lecture] Swift and Foundation- Tuples, Range, Data StructureStanford iOS Lecture 2020. 4. 13. 23:48
# Tuples
What is a Tuple?
- 스위프트의 타입 중 하나
- 서로 다른 타입들을 그룹으로 묶어서 하나의 타입을 만든다.
- 타입이 들어갈 자리라면 어디든지 튜플을 사용할 수 있다.
(You can use it anywhere you can use a type.)
# Range
- 무엇이든 연속적으로 표현할 수 있는 것의 양 끝 점을 가르킨다.
- Warning: A String subrange is not Range<Int> ( It is Range<String.Index> … we’ll talk later! )
- … 과 ..<
let array = ["a","b","c","d"] let subarray1 = array[2...3] let subarray2 = array[2..<3] for i in 1...10 { print(i) }
# Data structures in Swift
Class, Struct, Enum
- 모두 프로퍼티와 함수를 가질 수 있음.
- 모두 같은 방법으로 선언: 키워드 + 이름 + {}
- Enum은 저장, 계산 프로퍼티를 가질 수 없음
- Enum은 초기화 함수 필요 없음 (연관값과 구별되는 값들에 할당을 해주었기 때문)
- Inheritance : Class 만 가능
# Value vs. Reference
Value (Struct and Enum)
- Copied when passed as an argument to a function
- Copied when assigned to a different variable
- 값 타입은 함수에서 인자로 전달될 때 복사하고, 다른 변수에 할당할 때도 복사
- Remember that function parameters are constants
- You must note any func that can mutate a struct/enum with the keyword mutating
- Mutating func : 구조체의 값을 바꾸는 함수가 있는 구조체 함수 앞에 mutating을 붙여준다. (성능 향상을 위해)
Reference (Class)
- Stored in the heap and reference counted (automatically)
- 힙 메모리에 동일한 포인터 , 복사 X
- Constants pointers to a class (let) still can mutate by calling methods and changing properties
- let : 포인터가 변하지 않는다는 의미
- String, Double, Int, Array, Dictionary (Struct)
- Choosing which to use ?
- Usually you will choose class over struct.
- Struct tends to be more for fundamental types.
- Use of enum is situational (any time you have a type of data with discrete values).
- 클래스보다는 더 작고 스스로 자립하며, 값으로 복사하는게 말이 되고, 값 타입을 원하는 영역들
Class
Struct
Enum
Has property
O
O
O
has method
O
O
O
inheritance
O
X
X
pass by
ref
value
value
Init func
O
O
X
'Stanford iOS Lecture' 카테고리의 다른 글
[Stanford Lecture] Method & Property (0) 2020.04.14 [Stanford Lecture] MVC (0) 2020.04.13 [Stanford Lecture] What is iOS ? (0) 2020.04.13